Mybatis 基础

MyBatis 所解决的 JDBC 中存在的问题

  1. 数据库链接创建、释放频繁造成系统资源浪费从而影响系统性能
  2. Sql语句写在代码中造成代码不易维护。
  3. 向 sql 语句传参数麻烦,因为 sql 语句的 where 条件不一定,可能多也可能少,占位符需要和参数一一对应。

入门-增删查改

配置Mybatis-config.xml 并连接数据库

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql:///mybatis?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=Asia/Shanghai&amp;useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--        <mapper resource="com/huang/mybatis01/mapper/UserMapper.xml"/>-->
        <package name="com.huang.mybatis01.mapper"/>
    </mappers>
</configuration>

User.java

@Data
public class{
	private String username;
    private String address;
} 

UserMapper.java

package com.huang.mybatis01.mapper;

import com.huang.mybatis01.model.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @author: Zhiyu Huang
 * @create: 2021-03-04 14:59
 * @Description:
 */
public interface UserMapper {
    List<User> getAllUser();

    User getUserById(@Param("id") Integer id);

    // 不能 Integer updateUserById(@param("user")User user);
    Integer updateUserById(User user);

    Integer updateUserById2(@Param("username") String username,@Param("id") Integer id);

    Integer addUser(User user);

    Integer deleteUserById(Integer id);
}

UserMapper.xml

<?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.huang.mybatis01.mapper.UserMapper">
    <insert id="addUser" parameterType="com.huang.mybatis01.model.User">
        insert into usertest (username,address) values(#{username},#{address});
    </insert>

    <update id="updateUserById">
        update usertest set username = #{username} where id = #{id};
    </update>
    <update id="updateUserById2">
        update usertest set username = #{username} where id = #{id};
    </update>
    <delete id="deleteUserById">
        delete from usertest where id = #{id};
    </delete>


    <select id="getAllUser" resultType="com.huang.mybatis01.model.User">
        select * from usertest;
    </select>
    <select id="getUserById" resultType="com.huang.mybatis01.model.User">
        select * from usertest where id = #{id};
    </select>


</mapper>

parameterType

输入的参数类型

1 $#

在 JDBC 调用中,SQL 的执行,我们可以通过字符串拼接的方式来解决参数的传递问题,也可以通过占位符的方式来解决参数的传递问题。当然,这种方式也传递到 MyBatis 中,在 MyBatis 中,$ 相当于是参数拼接的方式,而 # 则相当于是占位符的方式。

一般来说,由于参数拼接的方式存在 SQL 注入的风险,因此我们使用较少,但是在一些特殊的场景下,又不得不使用这种方式。

2 简单类型

简单数据类型传递比较容易,像根据 id 查询一条记录就算是这一类的。

一旦用 @Param 指定了参数类型之后,可以省略掉参数类型,就是在 xml 文件中,不用定义 parameterType 了:

一个参数 id ,可以不用 @param 注解

User getUserById(@Param("id") Integer id);
// 等价于 User getUserById(Integer id);

对应的xml文件如下:

<select id="getUserById" resultType="com.huang.mybatis01.model.User">
    select * from usertest where id = #{id};
</select>

两个参数 ,必须使用 @param 注解

Integer updateUserById2(@Param("username") String username,@Param("id") Integer id);
//不能  Integer updateUserById2(String username,Integer id);
// 否则就不能通过指定的参数来获取参数

对应的xml 文件

<update id="updateUserById2">
update usertest set username = #{username} where id = #{id};
</update>
3 实体类 对象参数

例如添加一个用户:

Integer addUser(User user);

对应的 mapper 文件如下:

<insert id="addUser" parameterType="com.huang.mybatis01.model.User">
    insert into usertest (username,address) values(#{username},#{address});
</insert>

我们在引用的时候,直接使用属性名就能够定位到对象了。如果对象存在多个,我们也需要给对象添加 @Param 注解,如果给对象添加了 @Param 注解,那么对象属性的引用,会有一些变化。如下:

Integer addUser(@Param("user") User user);

如果对象参数添加了 @Param 注解,Mapper 中的写法就会发生变化:

<insert id="addUser" parameterType="com.huang.mybatis01.model.User">
    insert into usertest (username,address) values(#{user.username},#{user.address});
</insert>

注意多了一个前缀,这个前缀不是变量名,而是 @Param 注解中定义名称。

如果对象中还存在对象,用 . 继续取访问就可以了。

4 Map 参数

一般不推荐在项目中使用 Map 参数。如果想要使用 Map 传递参数,技术上来说,肯定是没有问题的。

Integer updateUsernameById(HashMap<String,Object> map);

XML 文件写法如下:

<update id="updateUsernameById">
    update user set username = #{username} where id=#{id};
</update>

**引用的变量名,就是 map 中的 key。**基本上和实体类是一样的,如果给 map 取了别名,那么在引用的时候,也要将别名作为前缀加上,这一点和实体类也是一样的。

resultType

resultType 是返回类型,在实际开发中,如果返回的数据类型比较复杂,一般我们使用 resultMap,但是,对于一些简单的返回,使用 resultType 就够用了。

resultType 返回的类型可以是简单类型,可以是对象,可以是集合,也可以是一个 hashmap,如果是 hashmap,map 中的 key 就是字段名,value 就是字段的值。

输出 pojo 对象和输出 pojo 列表在 sql 中定义的 resultType 是一样的。
返回单个 pojo 对象要保证 sql 查询出来的结果集为单条,内部使用 sqlSession.selectOne 方法调用,mapper 接口使用 pojo 对象作为方法返回值。返回 pojo 列表表示查询出来的结果集可能为多条,内部使用 sqlSession.selectList 方法,mapper 接口使用 List 对象作为方法返回值。

resultMap

解决数据库中的字段名和java代码中对象的属性名不一致的问题

在实际开发中,resultMap 是使用较多的返回数据类型配置。因为实际项目中,一般的返回数据类型比较丰富,要么字段和属性对不上,要么是一对一、一对多的查询,等等,这些需求,单纯的使用 resultType 是无法满足的,因此我们还需要使用 resultMap,也就是自己定义映射的结果集。

先来看一个基本用法:

首先在 mapper.xml 中定义一个 resultMap:

<!--
数据库中的字段名  id book  author   price
对象中的属性名    id boookName bookAuthor bookPrice
-->
<resultMap id="bookMap" type="com.huang.mybatis01.model.Book">
    <result column="id" property="id"/>
    <result column="book" property="bookName"/>
    <result column="author" property="bookAuthor"/>
    <result column="price" property="bookPrice"/>
</resultMap>

在这个 resultMap 中,id 用来描述主键,column 是数据库查询出来的列名,property 则是对象中的属性名。

然后在查询结果中,定义返回值时使用这个 ResultMap:

<select id="getAllBooks" resultMap="bookMap">
    select * from book;
</select>

动态 SQL

动态 SQL 是 MyBatis 中非常强大的一个功能。例如一些常见的查询场景:

  • 查询条件不确定
  • 批量插入
  • ….

这些类似需求,我们都可以通过 MyBatis 提供的动态 SQL 来解决。

MyBatis 中提供的动态 SQL 节点非常多。

if
/**
     * 1. 如果只有书名,则按书名查
     * 2. 如果只有作者名,则按作者查
     * 3. 两个都有,则按书名和作者两个条件查
     * 4. 都没有,则查全部
     */
List<Book> getAllBookByNameOrAuthor(Book book);

对应的xml文件

<resultMap id="bookMap" type="com.huang.mybatis01.model.Book">
        <result column="id" property="id"/>
        <result column="name" property="bookName"/>
        <result column="author" property="bookAuthor"/>
        <result column="price" property="bookPrice"/>
    </resultMap>

 
    <select id="getAllBookByNameOrAuthor" resultMap="bookMap" parameterType="com.huang.mybatis01.model.Book">
        select * from book
        <where>
            <if test="bookName!=null and bookName!=''">
                and  name = #{bookName}
            </if>
            <if test="bookAuthor!=null and bookAuthor!=''">
                and  author = #{bookAuthor}
            </if>
        </where>
    </select>
trim
set

set 关键字一般用在更新中。因为大部分情况下,更新的字段可能不确定,如果对象中存在该字段的值,就更新该字段,不存在,就不更新。例如如下方法:

现在,这个方法的需求是,根据用户 id 来跟新用户的其他属性,所以,user 对象中一定存在 id,其他属性则不确定,其他属性要是有值,就更新,没值(也就是为 null 的时候),则不处理该字段。

我们结合 set 节点,写出来的 sql 如下:

<update id="updateUser" parameterType="org.javaboy.mybatis.model.User">
    update user
    <set>
        <if test="username!=null">
            username = #{username},
        </if>
        <if test="address!=null">
            address=#{address},
        </if>
        <if test="favorites!=null">
            favorites=#{favorites},
        </if>
    </set>
    where id=#{id};
</update>
foreach

foreach 用来处理数组/集合参数。

例如,我们有一个批量查询的需求:

List<User> getUserByIds(@Param("ids")Integer[] ids);

对应的 XML 如下:

<select id="getUserByIds" resultType="org.javaboy.mybatis.model.User">
    select * from user where id in
    <foreach collection="ids" open="(" close=")" item="id" separator=",">
        #{id}
    </foreach>
</select>

在 mapper 中,通过 foreach 节点来遍历数组,collection 表示数组变量,open 表示循环结束后,左边的符号,close 表示循环结束后,右边的符号,item 表示循环时候的单个变量,separator 表示循环的元素之间的分隔符。

注意,默认情况下,无论你的数组/集合参数名字是什么,在 XML 中访问的时候,都是 array,开发者可以通过 @Param 注解给参数重新指定名字。

例如我还有一个批量插入的需求:

Integer batchInsertUser(@Param("users") List<User> users);

然后,定义该方法对应的 mapper:

<insert id="batchInsertUser">
    insert into user (username,address) values 
    <foreach collection="users" separator="," item="user">
        (#{user.username},#{user.address})
    </foreach>
</insert>

然后,在 Main 方法中进行测试:

    public static void main(String[] args) {
        SqlSessionFactory instance = SqlSessionFactoryUtils.getInstance();
        SqlSession sqlSession = instance.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = new ArrayList<>();
        User u1 = new User();
        u1.setUsername("zhangsan");
        u1.setAddress("shenzhen");
        users.add(u1);
        User u2 = new User();
        u2.setUsername("lisi");
        u2.setAddress("广州");
        users.add(u2);
        mapper.batchInsertUser(users);
        sqlSession.commit();
    }
}
sql 片段

有的时候,我们可能会将一些功能的部分抽取出来,方便复用!

大家知道,在 SQL 查询中,一般不建议写 *,因为 select * 会降低查询效率。但是,每次查询都要把字段名列出来,太麻烦。这种使用,我们可以利用 SQL 片段来解决这个问题。

例如,我们先在 mapper 中定义一个 SQL 片段:

<sql id="Base_Column">
    id,usename,address
</sql>

然后,在其他 SQL 中,就可以引用这个变量

<select id="getUserByIds" resultType="org.javaboy.mybatis.model.User">
    select <include refid="Base_Column" /> from user where id in
    <foreach collection="ids" open="(" close=")" item="id" separator=",">
        #{id}
    </foreach>
</select>

又如

<sql id="if-title-author">
    <if test="title!=null">
        title = #{title}
    </if>
    <if test="author!=null">
        and author = #{author}
    </if>
</sql>

在需要使用的地方使用Include标签引用即可

<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <include refid="if-title-author"></include>
    </where>
</select>
bind

定义变量,方便引用

 /**
     * 按姓氏查书
     * @param author
     * @return
     */
List<Book> getBookByAuthor(@Param("author") String author);

对应的xml文件如下

<select id="getBookByAuthor" resultMap="bookMap">
    <bind name="authorLike" value="author+'%'"/>
    SELECT * FROM book WHERE author LIKE #{authorLike};
</select>
<!--或者-->
<select id="getBookByAuthor" resultMap="bookMap">
    SELECT * FROM book WHERE author LIKE contact('%',#{author},'%');
</select>

测试

@Test
public void getBookByAuthor() {
    List<Book> list = bookMapper.getBookByAuthor("鲁");
    for (Book book : list) {
        System.out.println(book);
    }
}
choose (when, otherwise)

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

<select id="findActiveBlogLike"
  resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose> <!--只会执行一个-->
 <when test="title != null">
   AND title like #{title}
 </when>
 <when test="author != null and author.name != null">
   AND author_name like #{author.name}
 </when>
 <otherwise>
   AND featured = 1
 </otherwise>
</choose>
</select>

主键回填

方式一

使用 useGeneratedKeys="true" 自动增长的key,并复制给 keyProperty="id"

接口

Integer addUser(User user);

对应的xml文件写法

<insert id="addUser" parameterType="com.huang.mybatis01.model.User" useGeneratedKeys="true" keyProperty="id">
	insert into usertest (username,address) values(#{username},#{address});
</insert>

测试

@Test
public void addUser() {
    User user = new User();
    user.setUsername("testname2");
    user.setAddress("testaddress2");
    Integer integer = userMapper.addUser(user);
    sqlSession.commit();
    // 主键回填之后,user 对象的id 就会有值,否则没值
    System.out.println("user = " + user);
}
方式二
<insert id="addUser" parameterType="com.huang.mybatis01.model.User">
    <selectKey keyProperty="id" resultType="java.lang.Integer" order="AFTER">
        select last_insert_id();
    </selectKey>
    insert into usertest (username,address) values(#{username},#{address});
</insert>
<!--
表示执行完  insert into usertest (username,address) values(#{username},#{address}); 之后就执行 select last_insert_id(); 并把查询之后的值复制给 id 
-->

高级查询

一对一查询

环境信息:例如:每本书都有一个作者,作者都有自己的属性,根据这个,我来定义两个实体类:两个表,分别是author,article

两个实体类 如下:

Article

@Data
public class Article {
    private Long id;
    private String title;
    private String content;
    private Author author;
}

Author

public class Author {
    private Long id;
    private String name;
    private Integer age;
}

需求:

查询所有的文章以及对应的作者信息

接口

public interface ArticleMapper {
    List<Article> getAllArticle();
}

对应的XMl文件内容如下(情况一)

<?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.huang.mybatis01.mapper.ArticleMapper">

    
    <resultMap id="BaseArticleMap" type="com.huang.mybatis01.model.Article">
        <id property="id" column="id"></id>
        <result property="title" column="title"></result>
        <result property="content" column="content"></result>
    </resultMap>

    <!--不统一前缀  columnPrefix="author_"  -->
    <resultMap id="getAllArticle" type="com.huang.mybatis01.model.Article" extends="BaseArticleMap">
        <association property="author" javaType="com.huang.mybatis01.model.Author">
            <id property="id" column="author_id"/>
            <result property="name" column="author_name"/>
            <result property="age" column="author_age"/>
        </association>
    </resultMap>
    <!--统一前缀  columnPrefix="author_"  -->
    <resultMap id="getAllArticle" type="com.huang.mybatis01.model.Article" extends="BaseArticleMap">
        <association property="author" columnPrefix="author_" javaType="com.huang.mybatis01.model.Author">
            <id property="id" column="id"/>
            <result property="name" column="name"/>
            <result property="age" column="age"/>
        </association>
    </resultMap>
    
    <select id="getAllArticle" resultMap="getAllArticle">
        SELECT a.*,au.`id` AS author_id,au.`name` AS author_name,au.age AS author_age
        FROM article AS a,author AS au
        WHERE a.`author_id`=au.`id`;
    </select>
</mapper>

对应的XMl文件内容如下(情况二)

<mapper namespace="com.huang.mybatis01.mapper.AuthorMapper">
    <resultMap id="BaseArticleMap" type="com.huang.mybatis01.model.Author">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="age" property="age"/>
    </resultMap>
</mapper>
<?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.huang.mybatis01.mapper.ArticleMapper">

    <resultMap id="BaseArticleMap" type="com.huang.mybatis01.model.Article">
        <id property="id" column="id"></id>
        <result property="title" column="title"></result>
        <result property="content" column="content"></result>
    </resultMap>

    <!--引用其他Mapper文件中的基本Map resultMap="com.huang.mybatis01.mapper.AuthorMapper.BaseArticleMap-->
    <resultMap id="getAllArticle2" type="com.huang.mybatis01.model.Article" extends="BaseArticleMap">
        <association property="author" javaType="com.huang.mybatis01.model.Author" columnPrefix="author_" resultMap="com.huang.mybatis01.mapper.AuthorMapper.BaseArticleMap">
        </association>
    </resultMap>


    <select id="getAllArticle" resultMap="getAllArticle2">
        SELECT a.*,au.`id` AS author_id,au.`name` AS author_name,au.age AS author_age
        FROM article AS a,author AS au
        WHERE a.`author_id`=au.`id`;
    </select>
</mapper>

association 节点用来描述一对一的关系。这个节点中的内容,和 resultMap 一样,也是 id,result 等,在这个节点中,我们还可以继续描述一对一。

一对多查询

一对多查询,也是一个非常典型的使用场景。比如用户和角色的关系,一个用户可以具备多个角色。

首先我们准备三个表:

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50717
Source Host           : localhost:3306
Source Database       : security

Target Server Type    : MYSQL
Target Server Version : 50717
File Encoding         : 65001

Date: 2018-07-28 15:26:51
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL,
  `nameZh` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('1', 'dba', '数据库管理员');
INSERT INTO `role` VALUES ('2', 'admin', '系统管理员');
INSERT INTO `role` VALUES ('3', 'user', '用户');

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `enabled` tinyint(1) DEFAULT NULL,
  `locked` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'root', '2a10RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', '1', '0');
INSERT INTO `user` VALUES ('2', 'admin', '2a10RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', '1', '0');
INSERT INTO `user` VALUES ('3', 'sang', '2a10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', '1', '0');

-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` int(11) DEFAULT NULL,
  `rid` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES ('1', '1', '1');
INSERT INTO `user_role` VALUES ('2', '1', '2');
INSERT INTO `user_role` VALUES ('3', '2', '2');java
INSERT INTO `user_role` VALUES ('4', '3', '3');
SET FOREIGN_KEY_CHECKS=1;

这三个表中,有用户表,角色表以及用户角色关联表,其中用户角色关联表用来描述用户和角色之间的关系,他们是一对多的关系。

然后,根据这三个表,创建两个实体类:

@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    private List<Role> roles;
}
@Data
public class Role {
    private Integer id;
    private String name;
    private String nameZh;
}

接下来,定义一个根据 id 查询用户的方法:

User getUserById(Integer id);
<resultMap id="UserWithRole" type="org.javaboy.mybatis.model.User">
    <id column="id" property="id"/>
    <result column="username" property="username"/>
    <result column="password" property="password"/>
</resultMap>
<resultMap id="UserWithRoles" type="org.javaboy.mybatis.model.User">
    <collection property="roles" ofType="org.javaboy.mybatis.model.Role">
        <id property="id" column="rid"/>
        <result property="name" column="rname"/>
        <result property="nameZh" column="rnameZH"/>
    </collection>
</resultMap>
    <!--
<resultMap id="UserWithRoles" type="org.javaboy.mybatis.model.User">
    <collection property="roles" ofType="org.javaboy.mybatis.model.Role" columnPrefix="r" resultMap="org.javaboy.mybatis.mapper.RoleMapper.BaseRoleMap">
    </collection>
</resultMap>
   -->
<select id="UserWithRoles" resultMap="UserWithRole">
    SELECT u.*,r.`id` AS rid,r.`name` AS rname,r.`nameZh` AS rnameZh FROM USER u,role r,user_role ur WHERE u.`id`=ur.`uid` AND ur.`rid`=r.`id` AND u.`id`=#{id}
</select>

鉴别映射器

关键字 : discriminator

根据 enable=1 的话就显示Role信息,使用UserWithRolesMap,=0就不显示Role信息,使用BaseUserMap

@Data
public class User {
    private Integer id;
    private String username;
    private String address;
    private List<Role> roles;
    private boolean enabled;
}

接口

List<User> getAllUsersWithRoles2();

java对应的xml文件

    <resultMap id="BaseUserMap" type="com.huang.mybatis01.model.User">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="address" column="address"/>
        <result property="enabled" column="enabled"/>
    </resultMap>



    <resultMap id="UserWithRolesMap" type="com.huang.mybatis01.model.User" extends="BaseUserMap">
        <collection property="roles" ofType="com.huang.mybatis01.model.Role" columnPrefix="role_"
                    resultMap="com.huang.mybatis01.mapper.RoleMapper.BaseRoleMap">
        </collection>
    </resultMap>

    <resultMap id="getAllUsersWithRoles2" type="com.huang.mybatis01.model.User">
        <discriminator javaType="int" column="enabled">
            <case value="1" resultMap="UserWithRolesMap"></case>
            <case value="0" resultMap="BaseUserMap"></case>
        </discriminator>
    </resultMap>

    <!--    鉴别映射器-->
    <select id="getAllUsersWithRoles2" resultMap="getAllUsersWithRoles2">
        SELECT u.*,r.`id` AS role_id,r.`name` AS role_name FROM usertest u
LEFT JOIN user_role ur ON ur.`uid`=u.`id`
LEFT JOIN roletest r ON r.id = ur.`rid`;
    </select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值