1.首先创建两个测试类
代码语言:javascript复制@Data
@TableName("z_test_grade")
public class ZTestGradeEntity implements Serializable {
private Integer id;
private String name;
private String address;
}
代码语言:javascript复制@Data
@TableName("z_test_teacher")
public class ZTestTeacherEntity implements Serializable {
@TableId(type = IdType.AUTO)
private Integer id;
private String name;
private Integer age;
private String categroy;
private String level;
private Integer gradeldId; //关联主表id
}
2.创建返回类Dto 用来接收查询出来的结果
代码语言:javascript复制@Data
public class ResultDto {
private Integer id;
private String name;
private String address;
private List<ZTestTeacherEntity> teacherList;
}
3.重点:然后配置xml
代码语言:javascript复制//<-- 关联集合就是用collection-->
<resultMap id="gradeMap" type="com.personal.modules.test.ResultDto">
<id column="id" property="id" />
<result column="name" property="name"/>
<result column="address" property="address"/>
<collection property="teacherList" ofType="com.personal.modules.test.ZTestTeacherEntity">
<id property="id" column="t_id" />
<result column="t_name" property="name"/>
<result column="t_age" property="age"/>
<result column="t_categroy" property="categroy"/>
<result column="t_level" property="level"/>
<result column="t_gradeldId" property="gradeldId"/>
</collection>
</resultMap>
常用的属性就不说了,特别要注意的是ofType这个要指向各自表的实体类,然后子表的column属性不要和主表重名,一旦重名就会出问题,不知道是不是我配置的问题,希望有大佬指教,反正不重名就可以 接下来就是查询语句了,很简单,只要别名和上面resultMap对的上就ok
4.SQL
代码语言:javascript复制//SQL:
<select id="test" resultMap="gradeMap">
SELECT
ztg.id,
ztg.name,
ztg.address,
ztt.id as t_id,
ztt.name as t_name,
ztt.age as t_age,
ztt.categroy as t_categroy,
ztt.level as t_level,
ztt.gradeld_id as t_gradeldId
FROM
z_test_grade ztg
LEFT JOIN z_test_teacher ztt ON ztt.gradeld_id = ztg.id
</select>
5.返回结果数据
代码语言:javascript复制{
"code":200,
"data":[
{
"id":1,
"name":"3年一班",
"address":"1楼",
"teacherList":[
{
"id":1,
"name":"宋元桥",
"age":50,
"categroy":"武当",
"level":"1",
"gradeldId":1
},
{
"id":2,
"name":"俞莲舟",
"age":43,
"categroy":"武当",
"level":"1",
"gradeldId":1
}
]
},
{
"id":2,
"name":"3年二班",
"address":"2楼",
"teacherList":[
{
"id":3,
"name":"张三",
"age":55,
"categroy":"武当",
"level":"1",
"gradeldId":2
}
]
}
]
}