首页 > 其他分享 >Mybatis的嵌套查询-column多条件

Mybatis的嵌套查询-column多条件

时间:2023-07-23 17:25:46浏览次数:38  
标签:utf8mb4 column 查询 嵌套 role user Mybatis id

Mybatis的嵌套查询

一、结构

创建三个表user role user_role

简单展示一下嵌套查询的例子,其实就是Collection放到 ResultMap,下一层把上一层的查询结果作为条件传入。

-- master.`user` definition

CREATE TABLE `user` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `age` int DEFAULT NULL,
  `name` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id_IDX` (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='用户表';
-- master.`role` definition

CREATE TABLE `role` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `role_name` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;	
-- master.user_role definition

CREATE TABLE `user_role` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `role_id` bigint NOT NULL COMMENT '角色ID',
  `user_id` bigint NOT NULL COMMENT '用户ID',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

二、动态SQL

1、多层子查询嵌套

<resultMap id="userResult" type="com.yangjiapo.asynch.entity.User">
    <id column="id" property="id" jdbcType="BIGINT"/>
    <result column="age" property="age" jdbcType="INTEGER"/>
    <result column="name" property="name" jdbcType="VARCHAR"/>
    <collection property="roleList" ofType="com.yangjiapo.asynch.entity.Role" column="{userId=id}"
                select="selectRoleForUser"/>
</resultMap>

构造了一个User对象的返回结果,当然,一个用户有多个角色,即返回一个List的角色列表。

这里需要注意的是ofType 属性,即返回嵌套的对象是哪一个。在selectRoleForUser查询中,是嵌套的查询,在上一级的查询结果中有user表的ID。

这里再column属性中可以指定查询条件,即上一层的查询结果user的id。

<select id="selectRoleForUser" resultType="com.yangjiapo.asynch.entity.Role">
        select r.* from `role` r
        left join user_role ur on ur.role_id = r.id
        where ur.user_id = #{userId}
   </select>

主查询如下

 <select id="selectRoleForUserList" resultMap="userResult">
        select * from user where id = #{id,jdbcType=BIGINT}
    </select>

2、关联查询嵌套结果

还有一种即直接关联查询,返回结果。

<resultMap id="BaseResultMap" type="com.yangjiapo.asynch.entity.User">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <result column="age" property="age" jdbcType="INTEGER"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <collection property="roleList" javaType="ArrayList" ofType="com.yangjiapo.asynch.entity.Role">
            <id column="role_id" property="id" jdbcType="BIGINT"/>
            <result column="role_name" property="roleName" jdbcType="VARCHAR"/>
        </collection>
    </resultMap>

这里需要注意的是,嵌套中的查询结果字段不要和主表一样。

只有一个查询。

<select id="selectUser" resultMap="BaseResultMap" parameterType="com.yangjiapo.asynch.entity.User">
        select u.*,r.id as role_id, r.role_name from user u
        left join user_role ur on ur.user_id = u.id
        left join `role` r  on r.id = ur.role_id
        <where>
            <if test="id != null">
                u.id = #{id,jdbcType=BIGINT}
            </if>
            <if test="name != null and name != ''">
                u.name = #{name}
            </if>
        </where>
    </select>

三、总结

嵌套查询,即是上层的查询结果可以作为下层的查询条件。在关联查询中也是一样,left join后面也是有条件关联。

column 字段中,它是一个 set 集合。如下

<resultMap id="entityResult" type="xxx">
        <collection property="yyyList" ofType="yyy" column="{yyyId=id,yyyName=xxx_name,yyyCode=xxx_code}"
        select="selectYYY"/>
    </resultMap>

标签:utf8mb4,column,查询,嵌套,role,user,Mybatis,id
From: https://www.cnblogs.com/Choleen/p/17575270.html

相关文章

  • 提取MyBatis中XML语法构造SQL的功能
    提取MyBatis中XML语法构造SQL的功能MyBatis能够使用*.xml来编辑XML语法格式的SQL语句,常用的xml标签有<where>,<if>,<foreach>等。偶然遇到一个场景,只想使用MyBatis的解析XML语法生成SQL的功能,而不需其他功能,于是在@Select打断点,跟踪代码执行,后续发现和XML有关的类主要在包路......
  • MyBatis 常用工具类
    SQL类MyBatis提供了一个SQL工具类,使用这个工具类,我们可以很方便在Java代码动态构建SQL语句StringnewSql=newSQL()({SELECT("P.ID,P.USERNAME,P.PASSWORD,P.FULLNAME");SELECT("P.LASTNAME,P.CREATEDON,P.UPDATEDON");FROM("PERSONP");FR......
  • SpringBoot项目集成Mybatis Generator代码生成器
    添加依赖在项目的pom.xml文件中添加以下依赖<!--mybatisgenerator自动生成代码插件--><plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId>......
  • MyBatisPlus公共字段自动填充
    公共字段自动填充公共字段新增员工,修改、编辑员工信息时,都需要设置创建时间,修改时间等操作,这些操作过于重复、繁琐,为了有更快捷高效的,MyBatisPlus提供了公共字段自动填充功能,当我们执行insert和update操作时才执行MyBatisPLus公共字段自动填充就是在插入或者修改操作时,为指定字......
  • MyBatis-Plus文件上传方法
    网站的文件上传方法本地存储上传//本地存储方式MultipartFile接受文件@PostMapping("/save")publicResultsave(Stringusername,Integerage,MultipartFileimage)throwsIOException{log.info("文件:{},{},{}",username,age,image);......
  • cmake学习之-嵌套式cmake
    注意,此贴只是记录学习所得,并不是教程本人的帖子项目中会有很多cmake嵌套使用的情况总分式嵌套cmake的父子关系注意的式父节点的定义可以在子节点中使用,儿子节点只能在自身使用,称为继承1.顶层cmake的寻找方法add_subdirectory(子节点对应文件目录、、),其中只有第一个参数我......
  • Mybatis练习CRUD
    namespacenamespcae中的包名要和mapper接口中的方法名一致-id:就是对应的namespace中的方法名-resultType:Sql语法执行的返回值-parameter:  参数类型1、select(选择、查询语句)1、编写接口List<User>getUserList();2、编写mapper中sql语句<selectid="getUserLi......
  • ERROR 1709 (HY000): Index column size too large. The maximum column size is 767
    MySQL版本5.6.35在一个长度为512字符的字段上创建uniquekey报错CREATEDATABASEdpcs_metadataDEFAULTCHARACTERSETutf8;select*frominformation_schema.SCHEMATA;+--------------+--------------------+----------------------------+------------------------+---......
  • mybatisPlus
    mybatisPlusmybatisplus基础:mybatisspringspringmvc为什么要学习mybatisplus?可以解决大量时间所有的CRUD代码它都可以自动化完成简介简化jdbc操作简化mybatis快速入门网站:快速开始|MyBatis-Plus(baomidou.com)使用第三方依赖导入对应的依赖研究......
  • Mybatis笔记
    如何获得Mybatis?maven仓库:<!--https://mvnrepository.com/artifact/org.mybatis/mybatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version></depende......