mybatis查询返回一个对象中带有集合
364 字
2 分钟
mybatis查询返回一个对象中带有集合
1.首先创建两个测试类
@Data@TableName("z_test_grade")public class ZTestGradeEntity implements Serializable {
private Integer id;
private String name;
private String address;}@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 用来接收查询出来的结果
@Datapublic class ResultDto { private Integer id;
private String name;
private String address;
private List<ZTestTeacherEntity> teacherList;}3.重点:然后配置xml
//<-- 关联集合就是用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
//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.返回结果数据
{ "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 } ] } ]}文章分享
如果这篇文章对你有帮助,欢迎分享给更多人!
mybatis查询返回一个对象中带有集合
https://czxcly.cn/posts/mybatis查询返回一个对象中带有集合/ 相关文章 智能推荐
1
MyBatis在insert插入对象时,返回自增主键
技术文章 MyBatis在insert插入对象时,返回自增主键
2
MyBatis判断条件为等于的问题
技术文章 MyBatis判断条件为等于的问题
3
彻底卸载谷歌浏览器残留
其它教程 彻底卸载谷歌浏览器残留
4
VisualStudio安装时共享组件、工具和SDK安装位置不能更改的问题
技术文章 VisualStudio安装时共享组件、工具和SDK安装位置不能更改的问题
5
PyAutoGUI-pyautogui区域识别慢或总是失败
技术文章 PyAutoGUI-pyautogui区域识别慢或总是失败
随机文章 随机推荐