标签:head user 找不到 username col name 导致 map 使用
对象举例:
class User {
private String username;
private List<Wife> wifes;
}
class Wife {
}
封装出的List长度数据不正确
比如wifes数据应该有两条,但是查询出来只有一条
由于使用Mybatis-plus的分页
<resultMap id="BaseResultMap" type="com.xj.groupbuy.entity.User">
<id column="user_id" property="userId" jdbcType="VARCHAR"/>
<result column="username" property="username" jdbcType="VARCHAR"/>
</resultMap>
<resultMap id="UserWithWifes" type="com.xj.groupbuy.entity.User" extends="BaseResultMap">
<collection property="wifes" ofType="com.xj.groupbuy.entity.Wife">
<id column="wife_id" property="wifeId"/>
<result column="name" property="wifeName"/>
</collection>
</resultMap>
sql:
<select id="getAllUser" resultMap="UserWithWifes">
select
u.user_id,
u.username,
r.`wife_id` as wifeId,
r.`name` as wifeName
from `user` u
left join `wife` w on w.`husband_id`=u.`user_id`
</select>
如果采用collection封装的话
此时还是会查询出所有的数据
例如:
userId | username | wifeId | wifeName |
---|---|---|---|
1 | username | 1 | wifeName1 |
1 | username | 2 | wifeName2 |
1 | username | 3 | wifeName3 |
此时!如果分页,分一页两条数据的话就会将这三行数据分割开
导致封装出的List长度数据不正确
那么有观众可能会问了,那么会不会出现封装出两个一样的User呢
一个是user:{[wifeName1],[wifeName1 ]},一个是user{[wifeName3]}
答案是不会的,因为mybatis-plus最分页的时候会查询一次count来作为分页的依据
在执行这个sql的时候会计算一次count(*) from user,得到的结果是1,只有1个userId=1的数据
所以以上就会得出一个user:{[wifeName1],[wifeName1 ]},第三个wife就找不到了
直接使用Type会封装不上,有知道原因的可以评论区告诉小编哦
<resultMap id="BaseResultMap" type="com.xj.groupbuy.entity.User">
<id column="user_id" property="userId" jdbcType="VARCHAR"/>
<result column="username" property="username" jdbcType="VARCHAR"/>
</resultMap>
<resultMap id="WifeMap" type="com.xj.groupbuy.entity.Wife">
<id column="wife_id" property="wifeId"/>
<result column="name" property="wifeName"/>
</resultMap>
<resultMap id="UserWithWifes" type="com.xj.groupbuy.entity.User" extends="BaseResultMap">
<collection property="wifes" column="user_id" ofType="com.xj.groupbuy.entity.Wife" select="selectUserWifes">
<id column="wife_id" property="wifeId"/>
<result column="name" property="wifeName"/>
</collection>
</resultMap>
<!-- 这里是子查询 -->
<select id="selectUserWifes" resultMap="WifeMap">
select
w.`wife_id`,
w.`name`
from `wife` w
where w.`husband_id`=#{user_id}
</select>
<select id="getAllUser" resultMap="UserWithWifes">
select
u.user_id,
u.username
from `user` u
</select>
此时分页的时候,分页操作只会作用在User上,而对Wife没有影响
首先在mapper调用getAllUser后,会分页查询用户表,
当查询到第一个用户username时将其封装到UserWithWifes,
封装到wifes字段时,去执行子查询找到selectUserWifes方法,
然后根据column对应的user_id去做where查询,并把查询的结果封装成一个List
最后将封装完成的List
如果喜欢这篇文章的话,给小编点个大大的点赞好嘛
标签:head user 找不到 username col name 导致 map 使用
原文地址:https://www.cnblogs.com/flower1360/p/14685777.html