Mybatis多对一【association】
- 多对一
| /*第二步:在一方Mapper中添加根据编号检索*/ |
| <select id="get" resultType="com.hxh.basic.project.vo.GradeVo" parameterType="int"> |
| select * from grade where id = #{id}; |
| </select> |
| /*第三步:在多方Mapper中进行resultMap映射查询*/ |
| <resultMap id="TestMybatis" type="com.demo.pojo.Student" autoMapping="true"> |
| <id property="stuNo" column="stuNo"></id> |
| <association property="grade" javaType="com.demo.pojo.Grade" column="gradeId" |
| select="com.demo.dao.GradeDao.get"></association> |
| </resultMap> |
| |
| <select id="getAll" resultMap="TestMybatis"> |
| select * from student |
| </select> |
| |
| |
| |
| |
| { |
| "code": 0, |
| "message": "ok", |
| "data": [ |
| { |
| "id": 6, |
| "nickname": "Consumer", |
| "username": "于瑶", |
| "birthday": "2021-03-03T00:00:00", |
| "gradeVo": { |
| "id": 1, |
| "gradeNane": "一年级" |
| } |
| }, |
| { |
| "id": 7, |
| "nickname": "Company", |
| "username": "白志超", |
| "birthday": "2021-03-05T00:00:00", |
| "gradeVo": { |
| "id": 0, |
| "gradeNane": "幼儿园" |
| } |
| } |
| ] |
| } |
Mybatis一对多【collection】
- 一对多
| |
| |
| |
| |
| private List<UserVo> list; |
| /*第二步:在多方Mapper中添加根据状态检索*/ |
| <select id="get" resultType="com.hxh.basic.project.vo.UserVo" parameterType="int"> |
| select * from user where status = #{status}; |
| </select> |
| /*第三步:在一方Mapper中进行resultMap映射查询*/ |
| <resultMap id="resultMap" type="com.hxh.basic.project.vo.GradeVo" autoMapping="true"> |
| <id property="id" column="id"></id> |
| <collection property="list" ofType="com.hxh.basic.project.vo.UserVo" javaType="java.util.List" column="id" |
| select="com.hxh.basic.project.mapper.UserMapper.get"></collection> |
| </resultMap> |
| |
| <select id="getAll" resultMap="resultMap"> |
| select * from grade; |
| </select> |
| |
| |
| |
| |
| { |
| "code": 0, |
| "message": "ok", |
| "data": [ |
| { |
| "id": 0, |
| "gradeNane": "幼儿园", |
| "list": [ |
| { |
| "id": 5, |
| "nickname": "Producer", |
| "username": "高佳琪", |
| "birthday": "2021-03-03T00:00:00" |
| } |
| ] |
| }, |
| { |
| "id": 1, |
| "gradeNane": "一年级", |
| "list": [ |
| { |
| "id": 4, |
| "nickname": "LouisVan", |
| "username": "王莹", |
| "birthday": "2021-03-03T00:00:00" |
| } |
| ] |
| }, |
| { |
| "id": 2, |
| "gradeNane": "二年级", |
| "list": [] |
| } |
| ] |
| } |
概念
- 一对多和多对一
- 一对多:collection【多方添加一方的实体类、property:实体类变量名称、JavaType:实体类的返回值类型、column:当前的外键,如status、select:调用一方的ID查询】
- 多对一:association【一方添加多方集合、property:多方的变量名称、ofType:集合中多方的返回值类型、javaType:List包路径、column:当前ID,select:调用多方的根据外键查询】
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步