Spring Boot学习 - 配置MyBatis

2022-06-10 20:35:33 浏览数 (1)

先在pom.xml文件中引入MyBatis依赖和数据库驱动,这里我使用的是MySQL数据库

代码语言:javascript复制
        <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.0.4</version>
        </dependency>

不同版本的Spring Boot和MyBatis版本对应不一样,具体可查看官方文档:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/。

配置Druid数据源

引入时注意版本,有些版本会不兼容,选择适合的版本

代码语言:javascript复制
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

Druid是一个关系型数据库连接池,是阿里巴巴的一个开源项目,地址:https://github.com/alibaba/druid。Druid不但提供连接池的功能,还提供监控功能,可以实时查看数据库连接池和SQL查询的工作情况。

为了使用Druid连接池,需要在application.yml下配置,在resources下新建application.yml文件,配置如下:

代码语言:javascript复制
server:
  context-path: /web

spring:
  datasource:
    druid:
      # 数据库访问配置, 使用druid数据源
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: org.gjt.mm.mysql.Driver
      url: jdbc:mysql://47.113.122.133:3306/lixj?serverTimezone=UTC&autoReconnect=true&useUnicode=true&characterEncoding=UTF-8
      username: ******
      password: ******
      # 连接池配置
      initial-size: 5
      min-idle: 5
      max-active: 20
      # 连接等待超时时间
      max-wait: 30000
      # 配置检测可以关闭的空闲连接间隔时间
      time-between-eviction-runs-millis: 60000
      # 配置连接在池中的最小生存时间
      min-evictable-idle-time-millis: 300000
      validation-query: select '1' from dual
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      pool-prepared-statements: true
      max-open-prepared-statements: 20
      max-pool-prepared-statement-per-connection-size: 20
      # 配置监控统计拦截的filters, 去掉后监控界面sql无法统计, 'wall'用于防火墙
      filters: stat,wall
      # Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔
      aop-patterns: com.example.lixj.*


      # WebStatFilter配置
      web-stat-filter:
        enabled: true
        # 添加过滤规则
        url-pattern: /*
        # 忽略过滤的格式
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'

      # StatViewServlet配置
      stat-view-servlet:
        enabled: true
        # 访问路径为/druid时,跳转到StatViewServlet
        url-pattern: /druid/*
        # 是否能够重置数据
        reset-enable: false
        # 需要账号密码才能访问控制台
        login-username: druid
        login-password: druid123
        # IP白名单
        # allow: 127.0.0.1
        # IP黑名单(共同存在时,deny优先于allow)
        # deny: 192.168.1.218

      # 配置StatFilter
      filter:
        stat:
          log-slow-sql: true

数据库是我在自己服务器搭建的,查看搭建经过,如何在Linux安装MySQL数据库。

访问 http://localhost:8080/druid/login.html

登录后可以看到

在数据库新建表

代码语言:javascript复制
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `SNO` varchar(5) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `SNAME` varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `SSEX` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`SNO`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', '张三', '男');
INSERT INTO `student` VALUES ('2', '李四', '男');
INSERT INTO `student` VALUES ('3', '韩梅梅', '女');
INSERT INTO `student` VALUES ('4', '李梅', '女');

SET FOREIGN_KEY_CHECKS = 1;

创建对应的实体类

代码语言:javascript复制
@Data
public class Student implements Serializable {
    private String SNO;

    private String SNAME;

    private String SSEX;
}

创建一个包含基本CRUD的StudentMapper

代码语言:javascript复制
public interface StudentMapper {
    int add(Student student);
    int update(Student student);
    int deleteByIds(String sno);
    Student queryStudentById(String id);
}

使用注解方式

代码语言:javascript复制
@Component
@Mapper
public interface StudentMapper {

    @Insert("insert into student(sno,sname,ssex) values(#{sno},#{name},#{sex})")
    int add(Student student);

    @Update("update student set sname=#{name},ssex=#{sex} where sno=#{sno}")
    int update(Student student);

    @Delete("delete from student where sno=#{sno}")
    int deleteBysno(String sno);

    @Select("SELECT * FROM STUDENT WHERE SNO=#{SNO}")
    @Results(id = "student",value= {
            @Result(property = "SNO", column = "SNO", javaType = String.class),
            @Result(property = "SNAME", column = "SNAME", javaType = String.class),
            @Result(property = "SSEX", column = "SSEX", javaType = String.class)
    })
    Student queryStudentBySno(String sno);
}

然后编写服务层

代码语言:javascript复制
public interface IStudentService {

    int add(Student student);

    int update(Student student);

    int deleteById(String sno);

    Student queryById(String sno);
}

实现类

代码语言:javascript复制
@Service("studentService")
public class StudentServiceImpl implements IStudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public int add(Student student) {
        return this.studentMapper.add(student);
    }

    @Override
    public int update(Student student) {
        return this.studentMapper.update(student);
    }

    @Override
    public int deleteById(String sno) {
        return this.studentMapper.deleteBysno(sno);
    }

    @Override
    public Student queryById(String sno) {
        return this.studentMapper.queryStudentBySno(sno);
    }
}

Controller入口类

代码语言:javascript复制
@RestController
public class StudentController {

    @Autowired
    private StudentServiceImpl studentService;

    @RequestMapping( value = "/querystudent", method = RequestMethod.GET)
    public Student queryStudentBySno(String sno) {
        return this.studentService.queryById(sno);
    }
}

这里注意一个问题,在启动类上要加上 @MapperScan("com.example.lixj.mapper") ,否则会报错提示找不到 mapper文件 接下来可以启动项目了。

访问 http://localhost:8080/querystudent?sno=1

查看SQL监控的情况

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可 Links: https://lixj.fun/archives/springboot学习-配置mybatis

0 人点赞