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

mybatis中@One

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

不要放纵你的爱情,不要让欲望的利剑把你射中——莎士比亚

前两天写了mybatis一对多查询

今天写一下在代码中如何使用@One实现一对一的关联查询

这里的@One注解类名org.apache.ibatis.annotations.One

代码如下:

代码语言:javascript
复制
@Select("<script>" +
        "select *" +
        "        from user_role\n" +
        "        <where>" +
        "            <if test=\"userId != null\">" +
        "                AND user_id = #{userId}" +
        "            </if>" +
        "            <if test=\"roleId != null\">" +
        "                AND role_id = #{roleId}" +
        "            </if>" +
        "        </where>" +
        "</script>")
@Results({
        @Result(property = "id", column = "id"),
        @Result(property = "userId", column = "user_id"),
        @Result(property = "roleId", column = "role_id"),
        @Result(property = "role", javaType = RoleInfo.class, column = "role_id",
                one = @One(select = "com.ruben.mapper.RoleMapper.getById"))
})
List<UserRole> selectList(UserRole userRole);

然后执行单元测试:

代码语言:javascript
复制
@Test
void testOne(@Autowired UserRoleMapper userRoleMapper) {
    List<UserRole> userRoles = userRoleMapper.selectList(new UserRole() {{
        setUserId(1L);
    }});
    Assertions.assertEquals("admin", userRoles.get(0).getRole().getRoleName());
    Assertions.assertEquals("user", userRoles.get(1).getRole().getRoleName());
}

结果:

image-20230305223622356
image-20230305223622356

完整代码:

https://gitee.com/VampireAchao/simple-mybatis.git

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

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

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

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

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