1. Springboot集成Mybatis

文章目录

  • 1. springboot包装方式
  • 2. 自行构建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文件


DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.lzj.dao.UserDao">

    
    
    <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


DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	
    <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文件如下所示


<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.0modelVersion>

  <parent>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-parentartifactId>
      <version>2.3.11.RELEASEversion>
  parent>

  <groupId>com.lzjgroupId>
  <artifactId>MybatisDemoartifactId>
  <version>1.0-SNAPSHOTversion>

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

  <dependencies>
    
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-testartifactId>
    dependency>
    <dependency>
      <groupId>org.mybatis.spring.bootgroupId>
      <artifactId>mybatis-spring-boot-starterartifactId>
      <version>1.3.1version>
    dependency>
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
    dependency>
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.5.2version>
    dependency>

  dependencies>

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

project>

你可能感兴趣的:(Mybatis源码,mybatis,spring,boot,java)