Spring Boot集成MyBatis

Spring Boot集成MyBatis

MyBatis介绍

MyBatis是一个优秀的持久性框架,支持自定义SQL、存储过程和高级映射。MyBatis消除了几乎所有的JDBC代码和手动设置参数和检索结果。MyBatis可以使用简单的XML或注释进行配置,并映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

案例介绍

整合Spring Boot和MyBatis,使用XML方式对一张表进行插入、通过主键查找、查找所有记录

准备数据库

CREATE TABLE `oa_staff` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL COMMENT '名字',
  `gender` tinyint(4) NOT NULL DEFAULT '0' COMMENT '性别:0->男,1->女',
  `birthday` date DEFAULT NULL,
  `address` varchar(80) DEFAULT NULL COMMENT '住址',
  `native_place` varchar(80) DEFAULT NULL COMMENT '籍贯',
  `hiredate` date DEFAULT NULL COMMENT '入职日期',
  `gmt_create` datetime DEFAULT NULL,
  `gmt_modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COMMENT='员工信息'

生成项目模板

浏览器访问:
https://start.spring.io
Spring Boot集成MyBatis_第1张图片

相关依赖

		<dependency>
			<groupId>org.mybatis.spring.bootgroupId>
			<artifactId>mybatis-spring-boot-starterartifactId>
			<version>2.1.2version>
		dependency>
		<dependency>
			<groupId>mysqlgroupId>
			<artifactId>mysql-connector-javaartifactId>
			<scope>runtimescope>
		dependency>

添加MyBatis相关代码

这里通过XML方式操作数据库,与表结构相对应的Model类、Mapper接口、XML映射文件可以手动编辑,也可以通过一些生成工具生成,官方提供提供MyBatis Generator,国内有MyBatis-Plus的AutoGenerator 。
官方MyBatis Generator 插件的使用可以参考我写的这些文章

https://blog.csdn.net/seek_of/category_9971462.html

1、Model 类

src\main\java\com\example\demo\domain\OaStaff.java

package com.example.demo.domain;

import java.util.Date;

public class OaStaff {
     
    private Long id;
    private String name;
    private Byte gender;
    private Date birthday;
    private String address;
    private String nativePlace;
    private Date hiredate;
    private Date gmtCreate;
    private Date gmtModified;
 // 省略toString、getter和setter方法

2、mapper 接口

src\main\java\com\example\demo\mapper\OaStaffMapper.java

package com.example.demo.mapper;

import com.example.demo.domain.OaStaff;

import java.util.List;

public interface OaStaffMapper {
     
    int insert(OaStaff staff);

    OaStaff selectByPrimaryKey(Long id);

    List<OaStaff> selectAll();
}

3、XML映射器

src\main\resources\mybatis\mapper\OaStaffMapper.xml



<mapper namespace="com.example.demo.mapper.OaStaffMapper">
    <resultMap id="BaseResultMap" type="OaStaff">
        <id column="id" jdbcType="BIGINT" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="gender" jdbcType="TINYINT" property="gender" />
        <result column="birthday" jdbcType="DATE" property="birthday" />
        <result column="address" jdbcType="VARCHAR" property="address" />
        <result column="native_place" jdbcType="VARCHAR" property="nativePlace" />
        <result column="hiredate" jdbcType="DATE" property="hiredate" />
        <result column="gmt_create" jdbcType="TIMESTAMP" property="gmtCreate" />
        <result column="gmt_modified" jdbcType="TIMESTAMP" property="gmtModified" />
    resultMap>
    <insert id="insert" parameterType="com.example.demo.domain.OaStaff" useGeneratedKeys="true" keyProperty="id">
        insert into oa_staff (name, gender,birthday, address, native_place,hiredate, gmt_create, gmt_modified)
        values (#{name}, #{gender},#{birthday}, #{address}, #{nativePlace},#{hiredate}, #{gmtCreate}, #{gmtModified})
    insert>

    <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
        select id, name, gender, birthday, address, native_place, hiredate, gmt_create, gmt_modified
        from oa_staff
        where id = #{id}
    select>
    <select id="selectAll" resultMap="BaseResultMap">
        select id, name, gender, birthday, address, native_place, hiredate, gmt_create, gmt_modified
        from oa_staff
    select>
mapper>

配置

1、MyBatis xml配置文件
src\main\resources\mybatis\mybatis-config.xml



<configuration>
    <typeAliases>
        <package name="com.example.demo.domain"/>
    typeAliases>
    <mappers>
        <mapper resource="mybatis/mapper/OaStaffMapper.xml"/>
    mappers>
configuration>

2、application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.56.101:3306/db_example?characterEncoding=utf8&autoReconnect=true&serverTimezone=PRC
    username: root
    password: 123456
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
logging:
  level:
    root: info
    com:
      example:
        demo:
          mapper: TRACE

配置数据源、指定MyBatis配置文件位置、指定日志等级

3、启动类上加上注解org.mybatis.spring.annotation.MapperScan

package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
     

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

}

@MapperScan指定Mapper接口包名

测试

src\main\java\com\example\demo\component\MyBean.java

package com.example.demo.component;

import com.example.demo.domain.OaStaff;
import com.example.demo.mapper.OaStaffMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Component
public class MyBean implements CommandLineRunner {
     
    @Autowired
    private OaStaffMapper mapper;
    @Override
    public void run(String... args) {
     
        OaStaff staff = new OaStaff();
        staff.setName("葛斯文");
        staff.setAddress("北京市海淀区");
        staff.setBirthday(Date.from(LocalDate.of(1990, 11, 23).atStartOfDay(ZoneId.systemDefault()).toInstant()));
        staff.setGender(Byte.valueOf("1"));
        Date now = new Date();
        staff.setGmtCreate(now);
        mapper.insert(staff);
        OaStaff st = mapper.selectByPrimaryKey(1L);
        System.out.println(st);

        List<OaStaff> oaStaffs = mapper.selectAll();
        for (OaStaff os : oaStaffs) {
     
            System.out.println(os);
        }
    }
}

实现接口org.springframework.boot.CommandLineRunner可以在Spring Boot启动时候执行

测试插入、通过主键查询、查询所有记录接口

参考

spring-boot-starter Quick Start

mybatis-spring-boot-sample-xml

你可能感兴趣的:(Spring,Boot,spring,boot,mybatis)