前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >mybatis中@Many

mybatis中@Many

作者头像
阿超
发布2023-03-07 20:40:40
2490
发布2023-03-07 20:40:40
举报
文章被收录于专栏:快乐阿超快乐阿超

吃饭先喝汤,不用请药方——佚名

之前写了mybatis中@One

今天写个@Many

首先还是代码:

代码语言:javascript
复制
package com.ruben.mapper;

import com.ruben.pojo.po.UserInfo;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.session.RowBounds;

import java.util.List;

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM user_info")
    @Results({
            @Result(column = "id", property = "id"),
            @Result(column = "name", property = "name"),
            @Result(column = "age", property = "age"),
            @Result(column = "email", property = "email"),
            @Result(property = "userRoles", javaType = List.class, column = "userRole.userId = id",
                    many = @Many(select = "com.ruben.mapper.UserRoleMapper.selectListCursor"))
    })
    List<UserInfo> selectList(RowBounds rowBounds);
}

这里的UserRoleMapper.selectListCursor还是没动,感觉这里不应该是userRole.userId,直接使用userIdroleId会更好

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruben.mapper.UserRoleMapper">
    <resultMap id="userRole" type="com.ruben.pojo.po.UserRole">
        <result column="id" property="id"/>
        <result column="user_id" property="userId"/>
        <result column="role_id" property="roleId"/>
        <association property="role"
                     column="id = role_id"
                     javaType="com.ruben.pojo.po.RoleInfo"
                     select="com.ruben.mapper.RoleMapper.getById"
                     fetchType="lazy"/>
    </resultMap>

    <select id="selectListCursor" resultMap="userRole">
        select *
        from user_role
        <where>
            <if test="userRole.userId != null">
                AND user_id = #{userRole.userId}
            </if>
            <if test="userRole.roleId != null">
                AND role_id = #{userRole.roleId}
            </if>
        </where>
    </select>
</mapper>

然后结合之前的代码,这里写个单元测试:

代码语言:javascript
复制
@Test
void testMany(@Autowired UserMapper userMapper) {
    List<UserInfo> users = userMapper.selectList(new RowBounds(0, 5));
    Assertions.assertEquals("admin", users.get(0).getUserRoles().get(0).getRole().getRoleName());
    Assertions.assertEquals("user", users.get(0).getUserRoles().get(1).getRole().getRoleName());
}

运行结果:

image-20230306231317420
image-20230306231317420
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-03-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档