初始化

  1. 创建项目,勾选上 MyBatisFramework 和 MySQL module
  2. 填写配置文件 application.properties
#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=123456
  1. 确保数据库中包含表 user 的数据
  2. 添加与数据库表 user 对应的实体类 User
  3. 编写 UserMapper 接口,查询数据
@Mapper // mapper在运行时,会自动生成该接口的实现类对象,并且将该对象交给IOC容器管理
public interface UserMapper {
 
    @Select("select * from user")
    public List<User> list();
}
  1. 编写测试类,使用依赖注入形式从IOC容器中获取 UserMapper 类型的 bean 对象
@SpringBootTest //springboot整合单元测试的注解
class SpringbootMybatisQuickstartApplicationTests {
 
    @Autowired
    private UserMapper userMapper;
    @Test
    public void testListUser() {
        List<User> list = userMapper.list();
        System.out.println(list);
    }
}

配置SQL提示

首先在 IDEA 中链接数据库,精确到数据库名。

选择 sql 代码,右键菜单选择 “show content actions”,选择 “inject language or reference”,选择 “MySQL”

JDBC

    @Test
    public void testJDBC() throws Exception {
        // 1. 加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 2. 建立连接
        String url = "jdbc:mysql://localhost:3306/mybatis";
        String username = "root";
        String password = "995983";
        Connection connection = DriverManager.getConnection(url, username, password);
        // 3. 执行sql
        String sql = "select * from user";
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        // 4. 处理结果
        List<User> list = new ArrayList<>();
        while (resultSet.next()) {
            User user = new User();
            user.setId(resultSet.getInt("id"));
            user.setName(resultSet.getString("name"));
            user.setAge(resultSet.getShort("age"));
            user.setGender(resultSet.getShort("gender"));
            user.setPhone(resultSet.getString("phone"));
            list.add(user);
        }
        System.out.println(list);
        // 5. 释放资源
        statement.close();
        connection.close();
    }

Lombok

Lombok是一个实用的Java类库,能通过注解的形式自动生成构造器、getter/setter、equals、hashcode、toString等方法,并可以自动化生成日志变量,简化java开发、提高效率。

注解作用
@ToString会给类自动生成易阅读的toString方法
@EqualsAndHashCode根据类所拥有的非静态字段自动重写equals方法和hashCode方法
@Data提供了更综合的生成代码功能(@Getter+@Setter+@ToString+@EqualsAndHashCode)
@NoArgsConstructor为实体类生成无参的构造器方法
@AllArgsConstructor为实体类生成除了static修饰的字段之外带有各参数的构造器方法。

CRUD

删除

    @Delete("delete from emp where id = #{id}")
    public void deleteEmpById(Integer id);

#{} 占位符,预编译,性能高,防止 sql 注入

若要打开日志输出,则添加配置

mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

插入

    @Insert("insert into emp values(#{id},#{username},#{password},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")
    public void insertEmp(Emp emp);

插入(主键返回)

添加注解 @Options(keyProperty = "id", useGeneratedKeys = true)

修改

    @Update("update emp set username = #{username},password = #{password},name = #{name},gender = #{gender},image = #{image},job = #{job},entrydate = #{entrydate},dept_id = #{deptId},update_time = #{updateTime} where id = #{id}")
    public void updateEmp(Emp emp);

查询

数据库字段名和类属性名可能不同

解决方案:

  1. 查询 sql 语句起别名
  2. 使用 Result 注解手动映射
  3. 使用 mybatis 驼峰命名自动映射开关 mybatis.configuration.map-underscore-to-camel-case=true
    // 方案1
    @Select("select id,username,password,name,gender,image,job,entrydate,dept_id deptId,create_time createTime,update_time updateTime from emp where id = #{id}")
    public Emp getEmpById(Integer id);
    
    // 方案2
    @Results({
            @Result(column = "dept_id", property = "deptId"),
            @Result(column = "create_time", property = "createTime"),
            @Result(column = "update_time", property = "updateTime")
    })
    @Select("select * from emp where id = #{id}")
    public Emp getEmpById(Integer id);
 
    // 方案3
    @Select("select * from emp where id = #{id}")  
    public Emp getEmpById(Integer id);

@param 多参数查询时

    @Select("select * from emp limit #{start}, #{pageSize}")
    public List<Emp> page(@Param("start") Integer start, @Param("pageSize") Integer pageSize);

XML 映射文件

规范:

  1. XML映射文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包下(同包同名)。
  2. XML映射文件的namespace属性为Mapper接口全限定名一致。
  3. XML映射文件中sql语句的id与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.example.mapper.EmpMapper">
    <select id="getEmpById" resultType="com.example.pojo.Emp">
        select * from emp where id = #{id};
    </select>
 
    <select id="empList" resultType="com.example.pojo.Emp">
        select * from emp where name like concat('%', #{name}, '%') and gender = #{gender} and
        entrydate between #{begin} and #{end} order by update_time desc;
    </select>
 
    <update id="updateEmp">
        update emp set username = #{username},password = #{password},name = #{name},
            gender = #{gender},image = #{image},job = #{job},entrydate = #{entrydate},
            dept_id = #{deptId},update_time = #{updateTime} where id = #{id};
    </update>
 
    <insert id="insertEmp" useGeneratedKeys="true" keyProperty="id">
        insert into emp values(#{id},#{username},#{password},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime});
    </insert>
 
    <delete id="deleteEmp">
        delete from emp where id = #{id};
    </delete>
</mapper>

动态 SQL

  1. <if> 用于判断条件是否成立,如果条件为true,则拼接SQL。 形式:<if test="name!=null">..</if>
  2. <where> where元素只会在子元素有内容的情况下才插入where子句,而且会自动去除子 句的开头的AND或OR
  3. <set> 动态地在行首插入SET关键字,并会删掉末尾额外的逗号。(用在update语句中)
  4. <foreach collection="ids" item="id" separator="," open="(" close=")"> collection:集合名称 item:集合遍历出来的元素/项 separator:每一次遍历使用的分隔符 open:遍历开始前拼接的片段 close:遍历结束后拼接的片段
  5. <sql id="name"></sql> 定义可重用组件
  6. <include refid="name /> 引用组件