SpringBoot 整合 MyBatis

在这里插入图片描述

  1. 给数据库建表 [mysql] :
CREATE TABLE teacher(
    t_id INT PRIMARY KEY AUTO_INCREMENT,
    t_name VARCHAR(20)
);
CREATE TABLE class(
    c_id INT PRIMARY KEY AUTO_INCREMENT,
    c_name VARCHAR(20),
    teacher_id INT
);
ALTER TABLE class ADD CONSTRAINT fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teacher(t_id);

INSERT INTO teacher(t_name) VALUES('teacher1');
INSERT INTO teacher(t_name) VALUES('teacher2');

INSERT INTO class(c_name, teacher_id) VALUES('class_a', 1);
INSERT INTO class(c_name, teacher_id) VALUES('class_b', 2);
  1. 配置数据源相关属性 pom.xml :
<!--整合Durid数据源 start  -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.20</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--整合Durid数据源 end -->

        <!--整合MyBatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>
  1. 配置application.yml :
spring:
  thymeleaf:
    cache: false
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url:  jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
      username: root
      password: 123456
      #初始化大小,最小,最大
      initial-size: 5
      min-idle: 5
      max-active: 20
      #连接等待超时时间
      max-wait: 30000
      #配置检测可以关闭的空闲连接间隔时间
      time-between-eviction-runs-millis: 60000
      #配置连接在池中的最小生存时间
      min-evictable-idle-time-millis: 300000
      #用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。
      validation-query: select 'X'
      #申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
      test-while-idle: true
      #归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
      test-on-borrow: false
      #建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
      test-on-return: false
      #是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
      pool-prepared-statements: false
      max-open-prepared-statements: 20
      #要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100
      max-pool-prepared-statement-per-connection-size: 20
      #Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔
      aop-patterns: com.xj.demo.servie.*
      #合并多个DruidDataSource的监控数据
      use-global-data-source-stat: true
      #配置监控统计拦截的filters
      filter:
        #监控统计用的filter:stat
        stat:
          enabled: true
          merge-sql: true
          log-slow-sql: true
          #配置SQL慢的标准,执行时间超过slowSqlMillis的就是慢
          slow-sql-millis: 5000
        #防御sql注入的filter:wall
        wall:
          enabled: true
          config:
            #是否允许执行DELETE语句
            delete-allow: true
            #是否允许修改表
            drop-table-allow: true
        slf4j:
          enabled: true
          statement-executable-sql-log-enable: true
          #所有Statement相关的日志
          statement-log-enabled: false
mybatis:
  #指定全局配置文件的位置
  config-location: classpath:mybatis/mybatis-config.xml
  # 指定sql映射文件位置
  mapper-locations: classpath:mybatis/mapper/*.xml
  1. 配置启动类 MybatisMapperApplication :
package pers.th.mybatis_mapper;

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

/**
 * @MapperScan注解:
 * 作用:指定要变成实现类的接口所在的包,然后包下面的所有接口在编译之后都会生成相应的实现类
 * 添加位置:是在SpringBoot启动类上面添加
 */
@SpringBootApplication
@MapperScan(value = "pers.th.mybatis_mapper.mapper")
public class MybatisMapperApplication {

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

}
  1. 创建JavaBean
package pers.th.mybatis_mapper.entity;

/**
 * @Classname Teacher
 * @Description TODO teacher表实体类
 * @Date 2021/8/22 16:28
 * @Created by tanghao
 */
public class Teacher {
    
    private Integer tId;
    private String tName;

    public Integer gettId() {
        return tId;
    }

    public void settId(Integer tId) {
        this.tId = tId;
    }

    public String gettName() {
        return tName;
    }

    public void settName(String tName) {
        this.tName = tName;
    }
}

**注解版 (这里省略) **

  1. 配置文件版

TeacherMapper.java :

package pers.th.mybatis_mapper.mapper;

import pers.th.mybatis_mapper.entity.Teacher;

import java.util.List;

/**
 * @Classname TeacherMapper
 * @Description TODO
 * @Date 2021/8/22 16:33
 * @Created by tanghao
 */
public interface TeacherMapper {
    
    public List<Teacher> selectAll();
}

TeacherMapper.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="pers.th.mybatis_mapper.mapper.TeacherMapper">

    <!--    public List<Teacher> selectAll(); -->
    <select id="selectAll" resultType="pers.th.mybatis_mapper.entity.Teacher">
        SELECT * FROM teacher
    </select>

</mapper>

mybatis-config.xml :

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!--开启 驼峰式命名-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

MybatisMapperApplicationTests :

package pers.th.mybatis_mapper;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import pers.th.mybatis_mapper.entity.Teacher;
import pers.th.mybatis_mapper.mapper.TeacherMapper;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

@SpringBootTest
class MybatisMapperApplicationTests {

    @Autowired
    private TeacherMapper teacherMapper;

    @Test
    void contextLoads() throws SQLException {
        List<Teacher> teacherList = teacherMapper.selectAll();
        System.out.println(teacherList);
    }
}

效果图 :
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值