1. Springboot集成Mybatis


在深入理解mybatis源码之前,首先搭建mybatis的测试环境用于跟踪代码测试用。

下面介绍两种springboot集成mybatis运行环境的案例。一种是通过springboot包装mybatis的构建过程,一种是自行构建Mybatis的执行环境。

以查询user表为例,数据如下在这里插入图片描述

1. springboot包装方式

1.1 创建表对应的bean

package com.lzj.bean;

public class User {
    private int id;
    private String name;
    private int age;

    public User(){}

    public User(int id, String name, int age){
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

1.2 创建查询接口dao

package com.lzj.dao;

import com.lzj.bean.User;

public interface UserDao {
    public User selectOne(int id);
}

1.3 在resources下创建mapper文件

<?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">

<!--namespace为UserDao接口的全类名-->
<mapper namespace="com.lzj.dao.UserDao">

    <!--selectOne要与UserDao接口中的接口方法名一致-->
    <!--parameterType和resultType指定的类型除了基本类型外,自定义的类要用全类名-->
    <select id="selectOne" parameterType="int" resultType="com.lzj.bean.User">
        select * from user where id=#{id}
    </select>

</mapper>

1.4 创建查询数据库的服务

package com.lzj.service;

import com.lzj.bean.User;
import com.lzj.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    public void query(int id){
        User user = userDao.selectOne(id);
        System.out.println("hello :" + user);
    }
}

1.5 创建springboot的配置文件

server:
  prot: 8004

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/lzj?characterEncoding=utf8&serverTimezone=UTC
    username: root
    driver-class-name: com.mysql.cj.jdbc.Driver

#因为添加了mybatis-config.xml配置文件,所以此处就不用添加mybatis的配置了
#如果取消mybatis-config.xml配置文件,此处就要放开mybatis的配置
mybatis:
  mapper-locations: classpath*:mapper/*Mapper.xml

1.6 创建启动类

package com.lzj;

import com.lzj.service.UserService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.sql.SQLException;

@SpringBootApplication
@MapperScan(basePackages={"com.lzj.dao"})
public class AppDemo
{
    public static void main( String[] args ) throws SQLException {
        ConfigurableApplicationContext app = SpringApplication.run(AppDemo.class);
        UserService userService = app.getBean(UserService.class);
        userService.query(1); //1表示数据库表user中id的值
    }
}

启动后会把查询结果输出如下所示

hello :User{id=1, name='xiaowang', age=20}

2. 自行构建mybatis执行环境

通过此种方式搭建mybatis环境,首先创建的类User、UserDao、UserMapper与上面的一致。
2.1 创建一个工具类,工具类用于构建mybatis运行环境

package com.lzj.example;

import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransaction;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

@Component
public class MybatisUtil {

    public static final String url = "jdbc:mysql://localhost:3306/lzj?characterEncoding=utf8&serverTimezone=UTC";
    public static final String usr = "root";

    public Configuration configuration;
    public JdbcTransaction jdbcTransaction;


    public void init() throws SQLException {
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = factoryBuilder.build(MybatisUtil.class.getResourceAsStream("/mybatis-config.xml"));
        configuration = factory.getConfiguration();
        Connection connection = DriverManager.getConnection(url, usr, null);
        jdbcTransaction = new JdbcTransaction(connection);
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    public JdbcTransaction getJdbcTransaction() {
        return jdbcTransaction;
    }

    public void setJdbcTransaction(JdbcTransaction jdbcTransaction) {
        this.jdbcTransaction = jdbcTransaction;
    }
}

2.2 创建Executor执行器,用来执行查询数据库操作
此案例中创建的执行器为SimpleExecutor,具体该执行器用途会在后续文章中分析。

package com.lzj.example.executor;

import com.lzj.example.MybatisUtil;
import org.apache.ibatis.executor.SimpleExecutor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
import java.util.List;

@Component
public class SimpleExecutorExample {

    @Autowired
    private MybatisUtil mybatisUtil;

    public void SimpleExecutorTest() throws SQLException {
        Configuration configuration = mybatisUtil.getConfiguration();
        MappedStatement ms = configuration.getMappedStatement("com.lzj.dao.UserDao.selectOne");
        SimpleExecutor executor = new SimpleExecutor(mybatisUtil.getConfiguration(), mybatisUtil.getJdbcTransaction());
        List<Object> lists = executor.doQuery(ms, 1, RowBounds.DEFAULT, SimpleExecutor.NO_RESULT_HANDLER, ms.getBoundSql(1));
        System.out.println(lists.get(0));
    }
}

2.3 创建springboot配置文件
application.yml

server:
  prot: 8004

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/lzj?characterEncoding=utf8&serverTimezone=UTC
    username: root
    driver-class-name: com.mysql.cj.jdbc.Driver

2.4 创建mybatis的配置文件
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>
	<!---配置要解析的mapper-->
    <mappers>
        <mapper resource="mapper/UserMapper.xml"></mapper>
    </mappers>
</configuration>

2.5 创建启动类

package com.lzj;

import com.lzj.example.MybatisUtil;
import com.lzj.example.executor.SimpleExecutorExample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.sql.SQLException;

@SpringBootApplication
public class AppDemo
{
    public static void main( String[] args ) throws SQLException {
        ConfigurableApplicationContext app = SpringApplication.run(AppDemo.class);
        MybatisUtil mybatisUtil = app.getBean(MybatisUtil.class);
        SimpleExecutorExample simpleExecutorExample = app.getBean(SimpleExecutorExample.class);
        mybatisUtil.init();
        simpleExecutorExample.SimpleExecutorTest();
    }
}

启动测试类输出结果如下

User{id=1, name='xiaowang', age=20}

上述两种方式用到的pom文件如下所示

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.3.11.RELEASE</version>
  </parent>

  <groupId>com.lzj</groupId>
  <artifactId>MybatisDemo</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
      <maven.compiler.source>8</maven.compiler.source>
      <maven.compiler.target>8</maven.compiler.target>
  </properties>

  <dependencies>
    <!--引人spring boot所需包-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.2</version>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot集成MyBatis并进行接口查询,你需要进行以下几个步骤: 1. 首先,在Spring Boot的配置文件中配置数据库连接信息,包括数据库URL、用户名、密码和驱动类等。\[1\] 2. 创建一个启动类,使用@SpringBootApplication注解标记该类为Spring Boot的启动类。在该类的main方法中,使用SpringApplication.run方法启动应用程序,并获取MybatisUtil和SimpleExecutorExample的实例。\[2\] 3. 在pom.xml文件中添加MySQL驱动和MyBatis的起步依赖。\[3\] 4. 使用MyBatis提供的逆向工程生成实体Bean、映射文件和DAO接口。可以使用MyBatis Generator或者MyBatis Plus等工具来生成这些文件。生成后,你可以在DAO接口中定义各种查询方法。 5. 在需要进行查询的地方,通过@Autowired注解注入DAO接口的实例,然后调用相应的查询方法即可。 这样,你就可以在Spring Boot集成MyBatis并进行接口查询了。记得在配置文件中配置好数据库连接信息,并生成相应的实体Bean、映射文件和DAO接口。 #### 引用[.reference_title] - *1* *2* [1. Springboot集成Mybatis](https://blog.csdn.net/u010502101/article/details/127656247)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [SpringBoot集成MyBatis](https://blog.csdn.net/m0_67391377/article/details/124777417)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值