您的当前位置:首页正文

mybatis进行联表查询一对多无法映射采坑

2024-11-24 来源:个人技术集锦

最近做项目的时候,采用mybatis在Mapper文件中进行一对多映射时候,集合数据始终无法映射成功,为了解决这个不可能的问题停掉了项目,来寻找bug原因,结果真是让我大跌眼镜,只想说苦逼的程序员,傻逼的代码。下面贴出问题代码:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.CustomerMapper" >
<!--家长学生关系映射,这映射没有毛病-->
  <resultMap id="BaseResultMap" type="com.example.demo.CustomerVo">
    <id column="ID" property="id"  />
    <result column="PHONE_NUMBER" property="phoneNumber"  />
    <result column="NAME" property="name"  />
    <collection property="studentList" javaType="ArrayList" ofType="com.example.demo.StudentExtend">
      <id column="ST_ID" property="id"  />
      <result column="STUDENT_NAME" property="name"  />
    </collection>
  </resultMap>

  <select id="queryH5ById" resultMap="BaseResultMap" parameterType="java.lang.String">
    SELECT t_customer.ID, t_customer.NAME,t_customer.PHONE_NUMBER,
    t_student.ID ST_ID,t_student.NAME STUDENT_NAME
    FROM t_customer,t_student
    WHERE t_customer.ID = t_student.CUSTOMER_ID
  </select>
</mapper>        

把我坑惨的数据实体类

public class CustomerVo extends Customer {

    private List<StudentExtend> studentList;
    /** 出问题的数据实体 */
    public List<StudentExtend> getStudentList() {
        if (studentList == null) {
            return new ArrayList<>();
        }
        return studentList;
    }

    public void setStudentList(List<StudentExtend> studentList) {
        this.studentList = studentList;
    }
}

不想要的数据结果

[{"id":"7D55E2E2D0FF4BFAAD1679C8FBD2C500","name":"测试","phoneNumber":"13006300027","studentList":[]}]

正确的数据实体类

public class CustomerVo extends Customer {

    private List<StudentExtend> studentList;
    /** 这里千万不要有上面那种防止空对象操作 */
    public List<StudentExtend> getStudentList() {
        return studentList;
    }

    public void setStudentList(List<StudentExtend> studentList) {
        this.studentList = studentList;
    }
}

想要的数据结果

[{"id":"7D55E2E2D0FF4BFAAD1679C8FBD2C500","name":"测试","phoneNumber":"13006300027","studentList":[{"gradeName":"","id":"70FE959C6A6E4792A1BA147C91ED2B3D","name":"李小五","schoolName":""},{"gradeName":"","id":"B9A8171FAA504D3782A769F57EE9A6C4","name":"李小二","schoolName":""}]}]
显示全文