我是靠谱客的博主 饱满冰棍,这篇文章主要介绍Mybatis 一对一关联查询的两种方式:嵌套结果与嵌套查询嵌套结果嵌套查询,现在分享给大家,希望可以做个参考。

嵌套结果

Mapper 接口

复制代码
1
2
List<TUser> selectUserPosition1();

Mapper xml文件

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<resultMap id="BaseResultMap" type="TUser"> <id column="id" property="id" /> <result column="user_name" property="userName" /> <result column="real_name" property="realName" /> <result column="sex" property="sex" /> <result column="mobile" property="mobile" /> <result column="email" property="email" /> <result column="note" property="note" /> </resultMap> <resultMap id="userAndPosition1" extends="BaseResultMap" type="TUser"> <association property="position" javaType="TPosition" columnPrefix="post_"> <id column="id" property="id"/> <result column="name" property="postName"/> <result column="note" property="note"/> </association> </resultMap> <select id="selectUserPosition1" resultMap="userAndPosition1" > select a.id, user_name, real_name, sex, mobile, email, a.note, b.id post_id, b.post_name, b.note post_note from t_user a, t_position b where a.position_id = b.id </select>

t_user 表里有 position_id 字段

TUser 对象

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Data public class TUser{ private Integer id; private String userName; private String realName; private Byte sex; private String mobile; private String email; private String note; //持有了一个TPosition private TPosition position; }

使用

复制代码
1
2
3
4
5
List<TUser> list1 = mapper.selectUserPosition1(); for (TUser tUser : list1) { System.out.println(tUser); }

嵌套查询

Mapper 接口

复制代码
1
2
List<TUser> selectUserPosition2();

Mapper xml文件

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<select id="selectUserPosition2" resultMap="userAndPosition2" > select a.id, a.userName, a.realName, a.sex, a.mobile, a.position_id from t_user a </select> <resultMap id="userAndPosition2" extends="BaseResultMap" type="TUser"> <association property="position" fetchType="lazy" column="position_id" select="com.enjoylearning.mybatis.mapper.TPositionMapper.selectByPrimaryKey" /> </resultMap>

使用

复制代码
1
2
3
4
5
6
7
//因为配置了 fetchType="lazy" 不会调用 association 里面的方法 List<TUser> list2 = mapper.selectUserPosition2(); for (TUser tUser : list2) { //具体需要了才会调嵌套的查询,如果有缓存只会调用2次 System.out.println(tUser.getPosition()); }

这种方式会把所有的 TUser 查出来,t_user 有多少条,就会查出多少条

最后

以上就是饱满冰棍最近收集整理的关于Mybatis 一对一关联查询的两种方式:嵌套结果与嵌套查询嵌套结果嵌套查询的全部内容,更多相关Mybatis内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(108)

评论列表共有 0 条评论

立即
投稿
返回
顶部