SpringBoot整合Mybatis

准备工作

  1. 查看mybatis-spring-boot-starter启动器官方文档

http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

  1. 导入SpringBoot整合Mybatis所需要的依赖
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
  1. 配置数据库连接信息不变,使用Druid数据源
#配置springboot数据源和数据库驱动
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis_zr?serverTimezone=PRC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    password: root
    username: root
    #切换数据源
    type: com.alibaba.druid.pool.DruidDataSource
    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    druid:
      initialSize: 5
      minIdle: 5
      maxActive: 20
      maxWait: 60000
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true

      #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
      #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
      #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
      filters: stat,wall,log4j
      maxPoolPreparedStatementPerConnectionSize: 20
      useGlobalDataSourceStat: true
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
server:
  port: 80
  1. 测试数据库连接是否成功

  2. 创建实体类 ,使用Lombok插件

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    
    private Integer id;
    private String username;
    private String password;
    private Integer gender;
    private Date regist_time;

}

在这里插入图片描述
如果没有使用@Mapper注解标准Mapper接口类,则要在使用的类上加上注解@MapperScan注解进行扫描包下的Mapper接口

  1. 创建mapper目录以及对应的 Mapper 接口
//@Mapper : 表示本类是一个MyBatis的Mapper
@Mapper
@Repository
public interface UserMapper {

    //查询所有数据信息
    List<User> queryList();
    //根据id查询数据
    User queryById(@Param("id") int id);
    //添加一条数据
    int add(User user);
    //更新一条数据
    int update(User user);
    //根据id删除一条数据
    int delete(@Param("id") int id);


}
  1. 对应的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接口-->
<mapper namespace="com.chenhui.mapper.UserMapper">
<!--查询所有的数据-->
    <select id="queryList" resultType="user">
        select * from t_user
    </select>
<!--根据id查询一条数据-->
    <select id="queryById" resultType="user">
        select * from t_user where id = #{id}
    </select>
<!--插入一条数据-->
    <insert id="add" parameterType="user">
        insert into t_user (username,password,gender,regist_time)
        values(#{username},#{password},#{gender},#{regist_time})
    </insert>
<!--    更新一条数据-->
    <update id="update" parameterType="user">
        update t_user set username=#{username},password=#{password},gender=#{gender},
        regist_time=#{regist_time} where id=#{id}
    </update>
<!--    删除一条数据-->
    <delete id="delete" parameterType="_int">
        delete from t_user where id =#{id}
    </delete>
</mapper>

在这里插入图片描述

  1. 配置一些Mybatis的配置信息
#配置Mybatis一些配置,例如mapper.xml文件路径位置,以及实体类的别名
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.chenhui.pojo
  1. 编写controller类进行测试
@RestController
public class TestController {

    //注入UserMapper对象进行增删改查操作
    @Autowired
    UserMapper userMapper;

    @RequestMapping("/query")
    public List<User> query()  {
        //测试查询所有数据
        List<User> users = userMapper.queryList();
        return users;
    }

    @RequestMapping("/queryById")
    public User queryById()  {
        //根据id查询一条数据
        User user = userMapper.queryById(8);
        return user;
    }

    @RequestMapping("/add")
    public int add() {
        //添加一条数据
        int result = userMapper.add(new User(null, "hhh", "789", 1, new Date()));
        return result;
    }
    @RequestMapping("/update")
    public int update()  {
        //添加一条数据
        int result = userMapper.update(new User(15,"ch","8888",0,new Date()));
        return result;
    }

    @RequestMapping("/delete")
    public int delete()  {
        //添加一条数据
        int result = userMapper.delete(15);
        return result;
    }
}
  1. 启动项目测试成功即可!
### Spring Boot 整合 MyBatis 示例教程 #### 一、简介 在现代 Java 后端开发中,Spring BootMyBatis 是两个非常受欢迎的框架。前者提供了快速构建基于 Spring 的应用程序的能力,大大简化了配置过程;后者则是一款优秀的持久层框架,能够方便地与数据库进行交互[^1]。 #### 二、环境准备 为了顺利整合这两个强大的工具,在开始之前需确保已安装好 JDK (建议版本8及以上),Maven 构建工具以及 MySQL 数据库服务器。此外还需准备好 IDE 开发环境如 IntelliJ IDEA 或 Eclipse 等支持 Maven 工程的新版编辑器。 #### 三、创建 Spring Boot 项目并引入依赖项 可以通过 Spring Initializr 创建一个新的 Spring Boot 应用程序,并添加 `MyBatis Framework` 及其他必要的 Starter POM 文件中的依赖关系: ```xml <dependencies> <!-- Other dependencies --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies> ``` #### 四、配置数据源和其他设置 接下来要做的就是在项目的 resources 目录下找到名为 `application.properties` 的文件来定义连接池参数以及其他一些选项。这里给出一个简单的例子作为参考[^3]: ```properties spring.application.name=springboot-demo2 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=p@ssw0rd ``` 请注意 URL 中包含了 `useSSL=false` 参数用于关闭 SSL 加密通信,这通常是在本地测试环境中使用的做法; 而对于生产部署来说,则应该开启此功能以保障安全性。 #### 五、编写 Mapper 接口和实体类 现在可以着手设计业务逻辑部分了——即 CRUD 操作对应的 DAO 层接口及其 XML 映射文档。假设有一个 User 表结构如下所示: | id | name | |----|----------| | INT| VARCHAR(50)| 那么相应的 POJO 类型就应该是这样的样子: ```java public class User { private Integer id; private String name; // Getters and Setters... } ``` 与此同时还需要建立一个映射接口用来声明 SQL 查询语句的方法签名: ```java import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface IUserDao { List<User> findAll(); void insert(User user); } ``` 最后一步就是为上述方法提供具体的实现细节了, 即通过 XML 形式的 mapper 文件完成实际的数据访问操作描述. #### 六、启动服务验证成果 当所有准备工作都完成后就可以运行 Application.java 来检验整个流程是否正常工作了。如果一切顺利的话应当可以在控制台看到类似下面的日志输出表示成功建立了与目标表之间的关联[^2].
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值