当前位置: 代码迷 >> 综合 >> MyBatis-Plus中关联属性的查询(1对1,1对n,ResultMap)
  详细解决方案

MyBatis-Plus中关联属性的查询(1对1,1对n,ResultMap)

热度:59   发布时间:2023-09-06 14:06:12.0

近来在重构前面写的自用系统,重新写开发文档,接口文档,并使用新的技术。

关于Mybatis,新学了Mybatis-Plus(MP)框架,MP框架方便了很多数据库的操作,但是灵活性还是有些不足,特别是关联属性的查询(1对1,1对n)其中并没有封装,试验了一天,终于找到一个解决方法了,此贴也是自我的笔记。

实体类Teacher

//@Data采用的lombox,可以免写get/set等方法
@Data
public class Teacher {private int id;private String name;private String age;
}

实体类Student

//@Data采用的lombox,可以免写get/set等方法
@Data
public class Students {private int id;private String name;private String age;Private int tid;            //teacher的id值@TableField(exist = false)  //数据库中是无此字段的,MP中要排除掉private Teacher teacher;    //关联属性teacher
}

Mapper接口

//TeacherMapper继承BaseMapper即可,其中没有关联属性,直接使用MP提供的方法
@Mapper
@Component
public interface TeacherMapper extends BaseMapper<Teacher> {
}

@Mapper
@Component
public interface StudentMapper extends BaseMapper<Student> {//sql中有 ${ew.customSqlSegment} wrapper不能为null//Constants.WRAPPER枚举字符,其值为 "ew"@Results({@Result(column = "tid",property = "student",one = @One(select = "com.*.*.mapper.TeacherMapper.selectById"))})@Select("select * from student ${ew.customSqlSegment} ")List<Customer> selectStudentListWrapperNotNull(@Param(Constants.WRAPPER)Wrapper<Customer> wrapper);//wrapper为null的情况下,查询全部记录@Results({@Result(column = "tid",property = "student",one = @One(select = "com.*.*.mapper.TeacherMapper.selectById"))})@Select("select * from student")List<Customer> selectStudentListWrapperNull();
}

 sql中有“${ew.customSqlSegment}” (自定义sql段),wrapper是不能为null的,所以写了两个方法,在serviceImpl中进行组装

@Service
public class StudentServiceImpl implements StudentService {@AutowiredStudentMapper studentMapper = null;@Overridepublic List<Student> selectStudentList (Wrapper<Student> wrapper) {if (wrapper != null) {return studentMapper.selectStudentListWrapperNotNull(wrapper);} else {return studentMapper.selectStudentListWrapperNull();}}}

测试类

@AutowiredStudentService studentService = null;@Testvoid contextLoads() {//null为空,查询所有记录List<Student> list1 = studentService.selectStudentList(null);list1.forEach(System.out::println);//null不为空,条件查询List<Student> list2 = studentService.selectStudentList(Wrappers.<Student>lambdaQuery().orderByDesc(Student::getId()));list2.forEach(System.out::println);
}

此方法主要是采用注解方式,去掉xml配置,当然复杂的sql查询还是得采用xml

  相关解决方案