Spring Boot 集成 MyBatis (IDEA)

MyBatis简介

MyBatis 是支持普通的 SQL 查询,存储过程和高级映射的优秀持久层框架。 MyBatis 消除了几乎所有的 JDBC 代码和让参数得到手工设置以及对结果集的检索封装。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJO (Plain OId Java Object,普通的 Java对象) 映射成数据库中的记录。
优点:
● SQL 被统一提取出来,便于统一管理和优化
● SQL和代码解耦,将业务逻辑和数据访问逻辑分离,使系统的设计更清 晰、更易维护、更易单元测试
● 提供映射标签,支持对象与数据库的 ORM 字段关系映射
● 提供对象关系映射标签,支持对象关系组件维护
● 灵活书写动态 SQL ,支持各种条件来动态生成不同的 SQL
缺点:
● 编写 SQL 语句时工作量很大,尤其是字段多、关联表多时,更是如此
● SQL 语句依赖于数据库,导致数据库移植性差

MyBatis几个重要的概念:
Mapper配置: 可以使用基于 XML 的 Mapper 配置文件来实现,也可以使用基于 Java 注解的 MyBatis 注解来实现,甚至可以直接使用 MyBatis 提供的 API 来实现。
Mapper接口: 是指自行定义的一个数据操作接口,类似于通常所说的 DAO 接口。早期的 Mapper 接口需要自定义去实现,现在 MyBatis 会自动为Mapper 接口创建动态代理对象。Mapper 接口的方法通常与 Mapper 配置文件中的 select、 insert、 update、 delete 等 XML 结点存在一对应关系。
Executor: MyBatis 中所有的 Mapper 语句的执行都是通过 Executor 进行的,Executor 是 MyBatis 的一个核心接口。
SqlSession: 是 MyBatis 的关键对象,是执行持久化操作的独享,类似于JDBC 中的 Connection,SqlSession 对象完全包含以数据库为背景的所有执行 SQL 操作的方法,它的底层封装了JDBC 连接,可以用 SqlSession 实例来直接执行被映射的 SQL 语句。
SqlSessionFactory: 是 MyBatis 的关键对象,它是单个数据库映射关系经过编译后的内存镜像。SqlSessionFactory 对象的实例可以通过SqISessionFactoryBuilder 对象类获得,而 SqISessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration 的实例构建出。

Spring Boot 集成 MyBatis 步骤

  1. 创建项目
    不会构建 Spring Boot 项目的同学这里戳一戳 ☞ ☞Spring Boot入门及项目构建
    建项目时需要添加这两个依赖: MyBatis Framework、MySQL Driver

在这里插入图片描述

<!-- pom.xml 相关代码 -->
<dependency>
       <groupId>org.mybatis.spring.boot</groupId>
       <artifactId>mybatis-spring-boot-starter</artifactId>
       <version>2.1.3</version>
</dependency>

<dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
       <version>5.1.30</version>
</dependency>
  1. application.properties 配置相关信息
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root

mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.type-aliases-package=com.hxy.ch03.pojo

mybatis.configuration.cache-enabled=true
mybatis.configuration.lazy-loading-enabled=true
mybatis.configuration.auto-mapping-behavior=full
  1. 启动类
    在启动类中添加对 Mapper 包扫描 @MapperScan,Spring Boot 启动时会自动加载包路径下的 Mapper。或者直接在 Mapper 类上添加注解 @Mapper。
@SpringBootApplication
@MapperScan("com.hxy.ch03.mapper")
public class Ch03Application {

    public static void main(String[] args) {
        SpringApplication.run(Ch03Application.class, args);
    }

}
  1. 编码
    项目结构:
    在这里插入图片描述

编写实体类 User.Java:

public class User implements Serializable {
    private Long userId;
    private String userName;
    private String userPassword;
    private Long userRoleId;
    private Integer userFlag ;
    private Date creation_date;

	//省略 setter&getter

编写Mapper接口:

public interface UserMapper {
    public int insert(User user);
    public void delete(Long id);
    public void updata(User user);
    public User get(Long id);
    public List<User> findAll();
}

resources/mybatis/mapper 目录下创建并编写 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.hxy.ch03.mapper.UserMapper">   <!-- 实体类与数据库之间的映射体现在sql语句上面    接口 -->
    <insert id="insert" parameterType="User" >
        INSERT INTO `user`(`user_name`, `user_password`, `user_role_id`, `user_flag`, `creation_date`)
	        VALUES(#{userName},#{userPassword},#{userRoleId},#{userFlag},#{creation_date});
    </insert>

    <select id="findAll" resultType="User">
        SELECT * FROM `user`
    </select>
</mapper>
  1. 测试
    编写 Junit 测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class Ch03ApplicationTests {
    @Resource
    private UserMapper userMapper;

    @Test
    public void testinert(){
        User user = new User("小詺","999999",2L,3,new Date());
        int num = userMapper.insert(user);
        System.out.println(num);
    }

    @Test
    public void testfindAll(){
        List<User> list = userMapper.findAll();
        System.out.println(list);
    }
}

testinert()执行结果:
在这里插入图片描述


好文推荐:
Mybatis对象关系映射:https://www.cnblogs.com/binaway/p/9171587.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值