mybatis 注解方式多对多
原创
©著作权归作者所有:来自51CTO博客作者山阳糊涂的原创作品,请联系作者获取转载授权,否则将追究法律责任
类型表(type)字段:id,name
年级表(grade)字段:id,name
类型年级:typeid,gradeid
实体类(type):
public class ScTypeEntity {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private List<GradeEntity> grades;
public List<GradeEntity> getGrades() {
return grades;
}
public void setGrades(List<GradeEntity> grades) {
this.grades = grades;
}
}
实体类(grade)
public class GradeEntity {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
mapper类(type):
public interface ScTypeMapper {
@Select("select *,id typeid from jc_sctype where isdel<>1 order by id")
@Results({
@Result(property="grades",column = "typeid",
many = @Many(select = "com.jiapeng.mainsvr.mapper.GradeMapper.listBySctype"))
})
List<ScTypeEntity> listAll();
}
说明:
1、property 属性值是ScTypeEntity 中的grades
2、column 值是@Select 结果的typeid
3、@Many 值是查询关联结果的方法全路径
4、select *,id typeid from jc_sctype 中,将id再起个别名是防止结果中将id值设为null。
mapper类(grade):
public interface GradeMapper {
@Select("select a.* from jc_grade a\n" +
"right join jc_sc_grade b\n" +
"on a.id=b.gradeid\n" +
"where b.typeid=#{id}\n" +
"\n")
List<GradeEntity> listBySctype(String id);
}