MyBatis

ORMapping: Object Relationship Mapping 对象关系映射 对象指⾯向对象 关系指关系型数据库 Java 到 MySQL 的映射,开发者可以以⾯向对象的思想来管理数据库。

如何使用

  • 新建 Maven ⼯程,pom.xml
  1. <dependencies>
  2. <dependency>
  3. <groupId>org.mybatis</groupId>
  4. <artifactId>mybatis</artifactId>
  5. <version>3.4.5</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>mysql</groupId>
  9. <artifactId>mysql-connector-java</artifactId>
  10. <version>8.0.11</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.projectlombok</groupId>
  14. <artifactId>lombok</artifactId>
  15. <version>1.18.6</version>
  16. <scope>provided</scope>
  17. </dependency>
  18. </dependencies>
  19. <build>
  20. <resources>
  21. <resource>
  22. <directory>src/main/java</directory>
  23. <includes>
  24. <include>**/*.xml</include>
  25. </includes>
  26. </resource>
  27. </resources>
  28. </build>
  • 新建数据库
    1. use mybatis;
    2. create table t_account(
    3. id int primary key auto_increment,
    4. username varchar(11),
    5. password varchar(11),
    6. age int
    7. )
  • 新建数据表对应的实体类 Account
    1. package com.southwind.entity;
    2. import lombok.Data;
    3. @Data
    4. public class Account {
    5. private long id;
    6. private String username;
    7. private String password;
    8. private int age;
    9. }
  • 创建 MyBatis 的配置⽂件 config.xml,⽂件名可⾃定义
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    4. <configuration>
    5. <!-- 配置MyBatis运⾏环境 -->
    6. <environments default="development">
    7. <environment id="development">
    8. <!-- 配置JDBC事务管理 -->
    9. <transactionManager type="JDBC"></transactionManager>
    10. <!-- POOLED配置JDBC数据源连接池 -->
    11. <dataSource type="POOLED">
    12. <property name="driver" value="com.mysql.cj.jdbc.Driver">
    13. </property>
    14. <property name="url"
    15. value="jdbc:mysql://localhost:3306/mybatis?
    16. useUnicode=true&amp;characterEncoding=UTF-8"></property>
    17. <property name="username" value="root"></property>
    18. <property name="password" value="root"></property>
    19. </dataSource>
    20. </environment>
    21. </environments>
    22. </configuration>

使⽤原⽣接⼝

MyBatis 框架需要开发者⾃定义 SQL 语句,写在 Mapper.xml ⽂件中,实际开发中,会为每个实体 类创建对应的 Mapper.xml ,定义管理该对象数据的 SQL。

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.southwind.mapper.AccoutMapper">
  5. <insert id="save" parameterType="com.southwind.entity.Account">
  6. insert into t_account(username,password,age) values(#{username},#
  7. {password},#{age})
  8. </insert>
  9. </mapper>

namespace 通常设置为⽂件所在包+⽂件名的形式。

标签内容

insert 标签表示执⾏添加操作。

select 标签表示执⾏查询操作。

update 标签表示执⾏更新操作。

delete 标签表示执⾏删除操作。

id 是实际调⽤ MyBatis ⽅法时需要⽤到的参数。

parameterType 是调⽤对应⽅法时参数的数据类型。

自定义接口

  1. package com.southwind.repository;
  2. import com.southwind.entity.Account;
  3. import java.util.List;
  4. public interface AccountRepository {
  5. public int save(Account account);
  6. public int update(Account account);
  7. public int deleteById(long id);
  8. public List<Account> findAll();
  9. public Account findById(long id);
  10. }

创建接⼝对应的 Mapper.xml,定义接⼝⽅法对应的 SQL 语句。

statement 标签可根据 SQL 执⾏的业务选择 insert、delete、update、select。 MyBatis 框架会根据规则⾃动创建接⼝实现类的代理对象。

规则:

Mapper.xml 中 namespace 为接⼝的全类名。

Mapper.xml 中 statement 的 id 为接⼝中对应的⽅法名。 Mapper.xml 中 statement 的 parameterType 和接⼝中对应⽅法的参数类型⼀致。

Mapper.xml 中 statement 的 resultType 和接⼝中对应⽅法的返回值类型⼀致。

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.southwind.repository.AccountRepository">
  5. <insert id="save" parameterType="com.southwind.entity.Account">
  6. insert into t_account(username,password,age) values(#{username},#
  7. {password},#{age})
  8. </insert>
  9. <update id="update" parameterType="com.southwind.entity.Account">
  10. update t_account set username = #{username},password = #{password},age
  11. = #{age} where id = #{id}
  12. </update>
  13. <delete id="deleteById" parameterType="long">
  14. delete from t_account where id = #{id}
  15. </delete>
  16. <select id="findAll" resultType="com.southwind.entity.Account">
  17. select * from t_account
  18. </select>
  19. <select id="findById" parameterType="long"
  20. resultType="com.southwind.entity.Account">
  21. select * from t_account where id = #{id}
  22. </select>
  23. </mapper>

在 config.xml 中注册 AccountRepository.xml

调⽤接⼝的代理对象完成相关的业务操作

Mapper.xml

statement 标签:select、update、delete、insert 分别对应查询、修改、删除、添加操作。

parameterType:参数数据类型

1.基本数据类型,通过 id 查询 Account

  1. <select id="findById" parameterType="long"
  2. resultType="com.southwind.entity.Account">
  3. select * from t_account where id = #{id}
  4. </select>

2.String 类型,通过 name 查询 Account

  1. <select id="findByName" parameterType="java.lang.String"
  2. resultType="com.southwind.entity.Account">
  3. select * from t_account where username = #{username}
  4. </select>

3.包装类,通过 id 查询 Account

  1. <select id="findById2" parameterType="java.lang.Long"
  2. resultType="com.southwind.entity.Account">
  3. select * from t_account where id = #{id}
  4. </select>

4.多个参数,通过 name 和 age 查询 Account

  1. <select id="findByNameAndAge" resultType="com.southwind.entity.Account">
  2. select * from t_account where username = #{arg0} and age = #{arg1}
  3. </select>

5.Java Bean

  1. <update id="update" parameterType="com.southwind.entity.Account">
  2. update t_account set username = #{username},password = #{password},age =
  3. #{age} where id = #{id}
  4. </update>

resultType:结果类型

1.基本数据类型,统计 Account 总数

  1. <select id="count" resultType="int">
  2. select count(id) from t_account
  3. </select>

2.包装类,统计 Account 总数

  1. <select id="count2" resultType="java.lang.Integer">
  2. select count(id) from t_account
  3. </select>

3.String 类型,通过 id 查询 Account 的 name

  1. <select id="findNameById" resultType="java.lang.String">
  2. select username from t_account where id = #{id}
  3. </select>

4.Java Bean

  1. <select id="findById" parameterType="long"
  2. resultType="com.southwind.entity.Account">
  3. select * from t_account where id = #{id}
  4. </select>

及联查询

一对多

Student

  1. package com.southwind.entity;
  2. import lombok.Data;
  3. @Data
  4. public class Student {
  5. private long id;
  6. private String name;
  7. private Classes classes;
  8. }

Classes

  1. package com.southwind.entity;
  2. import lombok.Data;
  3. import java.util.List;
  4. @Data
  5. public class Classes {
  6. private long id;
  7. private String name;
  8. private List<Student> students;
  9. }

StudentRepository

  1. package com.southwind.repository;
  2. import com.southwind.entity.Student;
  3. public interface StudentRepository {
  4. public Student findById(long id);
  5. }

StudentRepository.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.southwind.repository.StudentRepository">
  5. <resultMap id="studentMap" type="com.southwind.entity.Student">
  6. <id column="id" property="id"></id>
  7. <result column="name" property="name"></result>
  8. <association property="classes" javaType="com.southwind.entity.Classes">
  9. <id column="cid" property="id"></id>
  10. <result column="cname" property="name"></result>
  11. </association>
  12. </resultMap>
  13. <select id="findById" parameterType="long" resultMap="studentMap">
  14. select s.id,s.name,c.id as cid,c.name as cname from student s,classes c
  15. where s.id = #{id} and s.cid = c.id
  16. </select>
  17. </mapper>

ClassesRepository

  1. package com.southwind.repository;
  2. import com.southwind.entity.Classes;
  3. public interface ClassesRepository {
  4. public Classes findById(long id);
  5. }

ClassesRepository.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.southwind.repository.ClassesRepository">
  5. <resultMap id="classesMap" type="com.southwind.entity.Classes">
  6. <id column="cid" property="id"></id>
  7. <result column="cname" property="name"></result>
  8. <collection property="students" ofType="com.southwind.entity.Student">
  9. <id column="id" property="id"/>
  10. <result column="name" property="name"/>
  11. </collection>
  12. </resultMap>
  13. <select id="findById" parameterType="long" resultMap="classesMap">
  14. select s.id,s.name,c.id as cid,c.name as cname from student s,classes c
  15. where c.id = #{id} and s.cid = c.id
  16. </select>
  17. </mapper>

多对多

Customer

  1. package com.southwind.entity;
  2. import lombok.Data;
  3. import java.util.List;
  4. @Data
  5. public class Customer {
  6. private long id;
  7. private String name;
  8. private List<Goods> goods;
  9. }

Goods

  1. package com.southwind.entity;
  2. import lombok.Data;
  3. import java.util.List;
  4. @Data
  5. public class Goods {
  6. private long id;
  7. private String name;
  8. private List<Customer> customers;
  9. }

CustomerRepository

  1. package com.southwind.repository;
  2. import com.southwind.entity.Customer;
  3. public interface CustomerRepository {
  4. public Customer findById(long id);
  5. }

CustomerRepository.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.southwind.repository.CustomerRepository">
  5. <resultMap id="customerMap" type="com.southwind.entity.Customer">
  6. <id column="cid" property="id"></id>
  7. <result column="cname" property="name"></result>
  8. <collection property="goods" ofType="com.southwind.entity.Goods">
  9. <id column="gid" property="id"/>
  10. <result column="gname" property="name"/>
  11. </collection>
  12. </resultMap>
  13. <select id="findById" parameterType="long" resultMap="customerMap">
  14. select c.id cid,c.name cname,g.id gid,g.name gname from customer c,goods
  15. g,customer_goods cg where c.id = #{id} and cg.cid = c.id and cg.gid = g.id
  16. </select>
  17. </mapper>

GoodsRepository

  1. package com.southwind.repository;
  2. import com.southwind.entity.Goods;
  3. public interface GoodsRepository {
  4. public Goods findById(long id);
  5. }

GoodsRepository.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.southwind.repository.GoodsRepository">
  5. <resultMap id="goodsMap" type="com.southwind.entity.Goods">
  6. <id column="gid" property="id"></id>
  7. <result column="gname" property="name"></result>
  8. <collection property="customers" ofType="com.southwind.entity.Customer">
  9. <id column="cid" property="id"/>
  10. <result column="cname" property="name"/>
  11. </collection>
  12. </resultMap>
  13. <select id="findById" parameterType="long" resultMap="goodsMap">
  14. select c.id cid,c.name cname,g.id gid,g.name gname from customer c,goods
  15. g,customer_goods cg where g.id = #{id} and cg.cid = c.id and cg.gid = g.id
  16. </select>
  17. </mapper>

MyBatis 动态 SQL

使⽤动态 SQL 可简化代码的开发,减少开发者的⼯作量,程序可以⾃动根据业务参数来决定 SQL 的组 成。

if标签

if 标签可以⾃动根据表达式的结果来决定是否将对应的语句添加到 SQL 中,如果条件不成⽴则不添加, 如果条件成⽴则添加。

  1. <select id="findByAccount" parameterType="com.southwind.entity.Account"
  2. resultType="com.southwind.entity.Account">
  3. select * from t_account where
  4. <if test="id!=0">
  5. id = #{id}
  6. </if>
  7. <if test="username!=null">
  8. and username = #{username}
  9. </if>
  10. <if test="password!=null">
  11. and password = #{password}
  12. </if>
  13. <if test="age!=0">
  14. and age = #{age}
  15. </if>
  16. </select>

where 标签

where 标签可以⾃动判断是否要删除语句块中的 and 关键字,如果检测到 where 直接跟 and 拼接,则 ⾃动删除 and,通常情况下 if 和 where 结合起来使⽤。

  1. <select id="findByAccount" parameterType="com.southwind.entity.Account"
  2. resultType="com.southwind.entity.Account">
  3. select * from t_account
  4. <where>
  5. <if test="id!=0">
  6. id = #{id}
  7. </if>
  8. <if test="username!=null">
  9. and username = #{username}
  10. </if>
  11. <if test="password!=null">
  12. and password = #{password}
  13. </if>
  14. <if test="age!=0">
  15. and age = #{age}
  16. </if>
  17. </where>
  18. </select>

choose 、when 、otherwise标签

choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

  1. <select id="findByAccount" parameterType="com.southwind.entity.Account"
  2. resultType="com.southwind.entity.Account">
  3. select * from t_account
  4. <where>
  5. <choose>
  6. <when test="id!=0">
  7. id = #{id}
  8. </when>
  9. <when test="username!=null">
  10. username = #{username}
  11. </when>
  12. <when test="password!=null">
  13. password = #{password}
  14. </when>
  15. <when test="age!=0">
  16. age = #{age}
  17. </when>
  18. <otherwise>
  19. </otherwise>
  20. </choose>
  21. </where>
  22. </select>

trim 标签

trim 标签中的 prefix 和 suffix 属性会被⽤于⽣成实际的 SQL 语句,会和标签内部的语句进⾏拼接,如 果语句前后出现了 prefixOverrides 或者 suffixOverrides 属性中指定的值,MyBatis 框架会⾃动将其删 除。

  1. <select id="findByAccount" parameterType="com.southwind.entity.Account"
  2. resultType="com.southwind.entity.Account">
  3. select * from t_account
  4. <trim prefix="where" prefixOverrides="and">
  5. <if test="id!=0">
  6. id = #{id}
  7. </if>
  8. <if test="username!=null">
  9. and username = #{username}
  10. </if>
  11. <if test="password!=null">
  12. and password = #{password}
  13. </if>
  14. <if test="age!=0">
  15. and age = #{age}
  16. </if>
  17. </trim>
  18. </select>

set 标签

set 标签⽤于 update 操作,会⾃动根据参数选择⽣成 SQL 语句。

  1. <update id="update" parameterType="com.southwind.entity.Account">
  2. update t_account
  3. <set>
  4. <if test="username!=null">
  5. username = #{username},
  6. </if>
  7. <if test="password!=null">
  8. password = #{password},
  9. </if>
  10. <if test="age!=0">
  11. age = #{age}
  12. </if>
  13. </set>
  14. where id = #{id}
  15. </update>

foreach 标签

foreach 标签可以迭代⽣成⼀系列值,这个标签主要⽤于 SQL 的 in 语句。

  1. <select id="findByIds" parameterType="com.southwind.entity.Account"
  2. resultType="com.southwind.entity.Account">
  3. select * from t_account
  4. <where>
  5. <foreach collection="ids" open="id in (" close=")" item="id"
  6. separator=",">
  7. #{id}
  8. </foreach>
  9. </where>
  10. </select>