MyBatis 快速入门和重点详解

x33g5p2x  于2021-12-06 转载在 其他  
字(12.5k)|赞(0)|评价(0)|浏览(240)

Mybatis简介

MyBatis 是一个优秀的基于 Java 的持久层框架,它内部封装了 JDBC,使开发者只需关注 SQL 语句本身,而不用再花费精力去处理诸如注册驱动、创建 Connection、配置 Statement 等繁杂过程。

Mybatis 通过 xml 或注解的方式将要执行的各种 Statement(Statement、PreparedStatement 等)配置起来,并通过 Java 对象和 Statement 中 SQL 的动态参数进行映射生成最终执行的 SQL 语句,最后由 MyBatis 框架执行 SQL 并将结果映射成 Java 对象并返回

MyBatis 与 Hibernate

Hibernate 框架是提供了全面的数据库封装机制的 “全自动” ORM,即实现了 POJO 和数据库表之间的映射,以及 SQL 的自动生成和执行。

相对于此,MyBatis 只能算作是 半自动 ORM。其着力点,是在 POJO 类与 SQL 语句之间的映射关系。也就是说,MyBatis 并不会为程序员自动生成 SQL 语句。具体的 SQL 需要程序员自己编写,然后通过 SQL 语句映射文件,将 SQL 所需的参数,以及返回的结果字段映射到指定 POJO。因此,MyBatis 成为了 “全自动” ORM 的一种有益补充。

MyBatis 的特点

  • 在 XML 文件中配置 SQL 语句,实现了 SQL 语句与代码的分离,给程序的维护带来了很大便利。
  • 因为需要程序员自己去编写 SQL 语句,程序员可以结合数据库自身的特点灵活控制 SQL 语句,因此能够实现比 Hibernate 等全自动 ORM 框架更高的查询效率,能够完成复杂查询。
  • 简单,易于学习,易于使用,上手快。

测试MyBatis 对象关系映射

POM

编写完相关代码后,我们可以使用单元测试查看 MyBatis 的执行效果,需要增加单元测试相关依赖,配置如下:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.17.RELEASE</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

定义实体类

tb_user 表为例,实体类代码如下:

public class TbUser implements Serializable {
    private Long id;
    private String username;
    private String password;
    private String phone;
    private String email;
    private Date created;
    private Date update;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getUpdate() {
        return update;
    }

    public void setUpdate(Date update) {
        this.update = update;
    }
}

定义数据访问接口

注意:Spring 集成 MyBatis 后,不需要手动实现 DAO 层的接口,所有的 SQL 执行语句都写在对应的关系映射配置文件中。

@Repository
public interface TbUserDao {

    /** * 查询全部用户信息 * @return */
    public List<TbUser> selectAll();
}

定义业务逻辑接口

public interface TbUserService {

    /** * 查询全部用户信息 * @return */
    public List<TbUser> selectAll();
}

实现业务逻辑接口

@Service
public class TbUserServiceImpl implements TbUserService {

    @Autowired
    private TbUserDao tbUserDao;

    @Override
    public List<TbUser> selectAll() {
        return tbUserDao.selectAll();
    }
}

定义映射文件

映射文件,简称为Mapper,主要完成 DAO 层中 SQL 语句的映射。映射文件名随意,一般放在src/resources/mapper 文件夹中。这里映射文件名称定为 TbUserMapper.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.funtl.my.shop.web.admin.dao.TbUserDao">
    <select id="selectAll" resultType="TbUser">
        SELECT
          a.id,
          a.username,
          a.password,
          a.phone,
          a.email,
          a.created,
          a.updated
        FROM
          tb_user AS a
    </select>
</mapper>

创建单元测试

所有工作准备就绪,我们就可以测试 MyBatis 是否能够正常执行了。创建一个单元测试类,代码如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-context.xml", "classpath:spring-context-druid.xml", "classpath:spring-context-mybatis.xml"})
public class TbUserServiceTest {

    @Autowired
    private TbUserDao tbUserDao;

    @Test
    public void testSelectAll() {
        List<TbUser> tbUsers = tbUserDao.selectAll();
        for (TbUser tbUser : tbUsers) {
            System.out.println(tbUser.getUsername());
        }
    }
}

parameterType

方法一:不需要写parameterType参数

public List<XXXBean> getXXXBeanList(String xxId, String xxCode);
<select id="getXXXBeanList" resultType="XXBean">

  select t.* from tableName where id = #{0} and name = #{1}  

</select>

由于是多参数那么就不能使用parameterType, 改用#{index}是第几个就用第几个的索引,索引从0开始

方法二:基于注解(最简单)

public List<XXXBean> getXXXBeanList(@Param("id")String id, @Param("code")String code);
<select id="getXXXBeanList" resultType="XXBean">

  select t.* from tableName where id = #{id} and name = #{code}  

</select>

由于是多参数那么就不能使用parameterType, 这里用@Param来指定哪一个

方法三:Map封装

public List<XXXBean> getXXXBeanList(HashMap map);
<select id="getXXXBeanList" parameterType="hashmap" resultType="XXBean">

  select 字段... from XXX where id=#{xxId} code = #{xxCode}  
  
</select>

其中hashmap是mybatis自己配置好的直接使用就行。map中key的名字是那个就在#{}使用那个,map如何封装就不用了我说了吧。

方法四:List封装

public List<XXXBean> getXXXBeanList(List<String> list);
<select id="getXXXBeanList" resultType="XXBean">
  select 字段... from XXX where id in
  <foreach item="item" index="index" collection="list" open="(" separator="," close=")">  
    #{item}  
  </foreach>  
</select>

总结

传递list和map在资源消耗上肯定远大于方法一和方法二,但是有一些特殊的情形需要传递list,比如你需要传递一个id集合并批量对id进行sql操作然后再返回等等。所以都需要了解。

resultType,resultMap

返回一般数据类型

比如要根据 id 属性获得数据库中的某个字段值。
mapper 接口:

//根据 id 获得数据库中的 username 字段的值
    String getEmpNameById(Integer id);

SQL 映射文件:

<!-- 指定 resultType 返回值类型时 String 类型的, string 在这里是一个别名,代表的是 java.lang.String 对于引用数据类型,都是将大写字母转小写,比如 HashMap 对应的别名是 'hashmap' 基本数据类型考虑到重复的问题,会在其前面加上 '_',比如 byte 对应的别名是 '_byte' -->
    <select id="getEmpNameById" resultType="string">
        select username from t_employee where id = #{id}
    </select>

返回 JavaBean 类型

比如根据某个字段获得数据库中的信息,把查询的结果信息封装成某个 JavaBean 类型的数据。
mapper 接口:

// 根据 id 查询信息,并把信息封装成 Employee 对象
    Employee getEmpById(Integer id);

SQL 映射文件:

<!-- 通过 resultType 指定查询的结果是 Employee 类型的数据 只需要指定 resultType 的类型,MyBatis 会自动将查询的结果映射成 JavaBean 中的属性 -->
    <select id="getEmpById" resultType="employee">
        select * from t_employee where id = #{id}
    </select>

返回List类型

有时候我们要查询的数据不止一条,比如:模糊查询,全表查询等,这时候返回的数据可能不止是一条数据,对于多数据的处理可以存放在List集合中。
mapper 接口:

// 假如是全表查询数据,将查询的数据封装成 Employee 类型的集合
    List<Employee> getAllEmps();

SQL 映射文件:

<!-- 注意这里的 resultType 返回值类型是集合内存储数据的类型,不是 'list' -->
    <select id="getAllEmps" resultType="employee">
        select * from t_employee
    </select>

返回Map类型

MyBatis 还支持将查询的数据封装成Map。

  1. 如果查询的结果是一条,我们可以把查询的数据以{表字段名, 对应的值}方式存入到Map中。
    mapper 接口:
// 根据 id 查询信息,并把结果信息封装成 Map 
    Map<String, Object> getEmpAsMapById(Integer id);

SQL 映射文件:

<!-- 注意这里的 resultType 返回值类型是 'map' -->
    <select id="getEmpAsMapById" resultType="map">
        select * from t_employee where id = #{id}
    </select>

下面把查询的结果数据贴出来供大家参考:

{email=zysheep@126.com,username=李四}
email 表中的字段名 username=字段对应的数据
  1. 如果查询的结果是多条数据,我们也可以把查询的数据以{表中某一字段名, JavaBean}方式来封装成Map。
    mapper 接口:
// 查询所有员工的信息,把数据库中的 'id' 字段作为 key,对应的 value 封装成 Employee 对象
    // @MapKey 中的值表示用数据库中的哪个字段名作 key
    @MapKey("id")
    Map<Integer, Employee> getAllEmpsAsMap();

SQL 映射文件:

<!-- 注意 resultType 返回值类型,不再是 'map',而是 Map 的 value 对应的 JavaBean 类型 -->
    <select id="getAllEmpsAsMap" resultType="employee">
        select * from t_employee
    </select>

下面是查询的结果 (只截取了一部分):

{16=Employee{id=16,username='James'}}

MyBatis 允许查询的结果封装成Map,这种机制是极好的。

resultType,resultMap的区别

1、如果只是返回一个值,比如说String或者int,那直接用resultType就行了,resultType="java.lang.String

<select id="getUserName" resultType="java.lang.String">
    select user_name from t_users
</select>

2、 如果sql查询结果返回的列名和实体类中的字段名一致,可以使用resultTypeMyBatis会自动把查询结果赋值给和字段名一致的字段。

@Data
public class Users {
    
    private Long id;
    private String userName;
    private Integer sex;

}

Mapper:

<select id="getUsersType" resultType="com.zysheep.mybatis.domain.Users">
    select user_name userName, sex from t_users
</select>

如果不一致,sql语句中可以使用别名的方式使其一致。

3、当sql的列名和实体类的列名不一致,这时就可以使用resultMap了。

<resultMap id="userMap" type="com.zysheep.mybatis.domain.Users">
    <id property="id" column="id"/>
    <result property="userName" column="user_name"/>
    <result property="sex" column="sex"/>
</resultMap>

<select id="getUsersMap" resultMap="userMap">
    select id, user_name, sex from t_users
</select>

property是实体类的字段名,column是sql查询的列名。

对于简单的映射,resultType和resultMap区别不大。但是resultMap功能更强大,可以通过设置typeHander来自定义实现功能。

MyBatis动态SQL

动态 SQL,主要用于解决查询条件不确定的情况:在程序运行期间,根据用户提交的查询条件进行查询。提交的查询条件不同,执行的 SQL 语句不同。若将每种可能的情况均逐一列出,对所有条件进行排列组合,将会出现大量的 SQL 语句。此时,可使用动态 SQL 来解决这样的问题。

动态 SQL,即通过 MyBatis 提供的各种标签对条件作出判断以实现动态拼接 SQL 语句。

这里的条件判断使用的表达式为 OGNL 表达式。常用的动态 SQL 标签有 <if><where><choose><foreach>等。

注意事项

在 mapper 的动态 SQL 中若出现大于号(>)、小于号(<)、大于等于号(>=),小于等于号(<=)等符号,最好将其转换为实体符号。否则,XML 可能会出现解析出错问题。

特别是对于小于号(<),在 XML 中是绝对不能出现的。否则,一定出错。

if 标签

对于该标签的执行,当 test 的值为 true 时,会将其包含的 SQL 片断拼接到其所在的 SQL 语句中。

本例实现的功能是:查询出满足用户提交查询条件的所有学生。用户提交的查询条件可以包含一个姓名的模糊查询,同时还可以包含一个年龄的下限。当然,用户在提交表单时可能两个条件均做出了设定,也可能两个条件均不做设定,也可以只做其中一项设定。

这引发的问题是,查询条件不确定,查询条件依赖于用户提交的内容。此时,就可使用动态 SQL 语句,根据用户提交内容对将要执行的 SQL 进行拼接

定义映射文件

为了解决两个条件均未做设定的情况,在where 后添加了一个“1=1”的条件。这样就不至于两个条件均未设定而出现只剩下一个 where,而没有任何可拼接的条件的不完整 SQL 语句。

<?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.lusifer.mybatis.dao.DynamicStudentDao">
    <!-- if -->
    <select id="selectByIf" resultType="com.lusifer.mybatis.entity.Student">
        SELECT
            id,
            name,
            age,
            score
        FROM
            student
        WHERE 1 = 1
        <if test="name != null and name != ''">
            AND name LIKE concat('%', #{name}, '%')
        </if>
        <if test="age != null and age > 0">
            AND age > #{age}
        </if>
    </select>
</mapper>

where 标签

<if/> 标签的中存在一个比较麻烦的地方:需要在where后手工添加 1=1 的子句。因为,若 where后的所有<if/>条件均为 false,而 where后若又没有 1=1 子句,则 SQL 中就会只剩下一个空的whereSQL 出错。所以,在 where 后,需要添加永为真子句 1=1,以防止这种情况的发生。但当数据量很大时,会严重影响查询效率。

定义映射文件

<!-- where-->
<select id="selectByWhere" resultType="com.lusifer.mybatis.entity.Student">
    SELECT
        id,
        name,
        age,
        score
    FROM
      student
    <where>
        <if test="name != null and name != ''">
            AND name LIKE concat('%', #{name}, '%')
        </if>
        <if test="age != null and age > 0">
            AND age > #{age}
        </if>
    </where>
</select>

choose 标签

该标签中只可以包含<when/> <otherwise/>,可以包含多个 <when/> 与一个 <otherwise/>。它们联合使用,完成 Java 中的开关语句 switch…case 功能。

本例要完成的需求是,若姓名不空,则按照姓名查询;若姓名为空,则按照年龄查询;若没有查询条件,则没有查询结果

foreach 标签-遍历数组

<foreach/> 标签用于实现对于数组与集合的遍历。对其使用,需要注意:

  • collection 表示要遍历的集合类型,这里是数组,即 array。
  • open、close、separator 为对遍历内容的 SQL 拼接。

本例实现的需求是,查询出 id 为 2 与 4 的学生信息。

定义映射文件

动态 SQL 的判断中使用的都是 OGNL 表达式。OGNL 表达式中的数组使用array 表示,数组长度使用array.length 表示。

<!-- foreach -->
<select id="selectByForeach" resultType="com.lusifer.mybatis.entity.Student">
    <!-- select * from student where id in (2, 4) -->
    SELECT
        id,
        name,
        age,
        score
    FROM
      student
         <!--不能识别写,必须是array表示数组-->
    <if test="array != null and array.length > 0">
        WHERE id IN
        <!--指定遍历集合类型为数组-->
        <foreach collection="array" open="(" close=")" item="id" separator=",">
            #{id}
        </foreach>
    </if>
</select>

foreach 标签-遍历集合

遍历集合的方式与遍历数组的方式相同,只不过是将 array 替换成了 list

遍历泛型为基本类型的 List

定义 DAO 接口

/** * 使用 foreach 标签以 list 基本类型的形式查询 * @param ids * @return */
public List<Student> selectByForeachWithListBase(List<Long> ids);

定义映射文件

<!-- foreach -->
<select id="selectByForeachWithListBase" resultType="com.lusifer.mybatis.entity.Student">
    <!-- select * from student where id in (2, 4) -->
    SELECT
        id,
        name,
        age,
        score
    FROM
      student
    <if test="list != null and list.size > 0">
        WHERE id IN
        <foreach collection="list" open="(" close=")" item="id" separator=",">
            #{id}
        </foreach>
    </if>
</select>

遍历泛型为自定义类型的 List

定义 DAO 接口

/** * 使用 foreach 标签以 list 自定义类型的形式查询 * @param students * @return */
public List<Student> selectByForeachWithListCustom(List<Student> students);

定义映射文件

<!-- foreach -->
<select id="selectByForeachWithListCustom" resultType="com.lusifer.mybatis.entity.Student">
    <!-- select * from student where id in (2, 4) -->
    SELECT
        id,
        name,
        age,
        score
    FROM
      student
    <if test="list != null and list.size > 0">
        WHERE id IN
        <foreach collection="list" open="(" close=")" item="student" separator=",">
            #{student.id}
        </foreach>
    </if>
</select>

sql 标签

<sql/> 标签用于定义 SQL 片断,以便其它 SQL标签复用。而其它标签使用该 SQL 片断, 需要使用<include/>子标签。该 <sql/>标签可以定义SQL 语句中的任何部分,所以<include/> 子标签可以放在动态SQL的任何位置

修改映射文件

<sql id="select">
    SELECT
        id,
        name,
        age,
        score
    FROM
      student
</sql>
<!-- foreach -->
<select id="selectByForeachWithListCustom" resultType="com.lusifer.mybatis.entity.Student">
    <!-- select * from student where id in (2, 4) -->
    <include refid="select" />

    <if test="list != null and list.size > 0">
        WHERE id IN
        <foreach collection="list" open="(" close=")" item="student" separator=",">
            #{student.id}
        </foreach>
    </if>
</select>

相关文章