1. Springboot集成Mybatis

这篇具有很好参考价值的文章主要介绍了1. Springboot集成Mybatis。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


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

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

以查询user表为例,数据如下1. Springboot集成Mybatis

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文件如下所示文章来源地址https://www.toymoban.com/news/detail-418438.html

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

到了这里,关于1. Springboot集成Mybatis的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • idea 搭建 SpringBoot 集成 mybatis

    编译器:IDEA 环境:win10,jdk1.8,maven3.5 数据库:mysql 5.7 一、打开IDEA新建项目 1. 如果你是第一次使用IDEA,那么你需要配置你本地的maven,点击右下角 Configure,如已配置请忽略此步骤 在下拉框中选择setting,然后如下图操作,选择自己本地的maven路径与maven配置文件 点击OK 2.新

    2024年02月15日
    浏览(30)
  • 使用SpringBoot集成Mybatis的详细步骤

    这里mybatis采用的是3.4.5版本,注意:mybatis3.4.0版本以上才支持@Mapper注解 相关依赖代码如下: pom文件完整代码如下: 导入pom文件后,若依赖报红,需要重新import下(点击下图里的刷新图标) 这边主要设计到的包有Controller(控制层),Entity(实体层),Service(接口层),ServiceImpl(接口

    2024年02月09日
    浏览(31)
  • SpringBoot集成Mybatis Plus【附源码】

    作为SpringBoot集成中间件其中的一篇文章吧,既然打算出这么一个系列了,争取做到虽小却全,又精又美的一个系列吧。 Mybatis Plus作为我入行以来,一直接触的一个中间件,也必须集成一下。同时也为初学者带来一些帮吧。 本文拆分自笑小枫-SpringBoot系列,更为精简的介绍了

    2024年01月16日
    浏览(31)
  • SpringBoot与MyBatis零XML配置集成和集成测试

    原文地址:https://ntopic.cn/p/2023070801/ 源代码先行: Gitee本文介绍的完整仓库:https://gitee.com/obullxl/ntopic-boot GitHub本文介绍的完整仓库:https://github.com/obullxl/ntopic-boot 在Java众多的ORM框架里面,MyBatis是比较轻量级框架之一,既有数据表和Java对象映射功能,在SQL编写方面又不失原生

    2024年02月12日
    浏览(45)
  • 【SpringBoot】| ORM 操作 MySQL(集成MyBatis)

    目录 一:ORM 操作 MySQL  1. 创建 Spring Boot 项目 2. @MapperScan 3. mapper文件和java代码分开管理 4. 事务支持 使用MyBatis框架操作数据, 在SpringBoot框架集成MyBatis,使用步骤: (1)mybatis起步依赖 : 完成mybatis对象自动配置, 对象放在容器中 (2)pom.xml 指定把src/main/java目录中的xml文

    2024年02月14日
    浏览(31)
  • SpringBoot集成MyBatis-yml方式详解

            简介:spring boot整合mybatis开发web系统目前来说是市面上主流的框架,每个Java程序和springboot mybatis相处的时间可谓是比和自己女朋友相处的时间都多,但是springboot mybatis并没有得到你的真爱,因为你只是为了养活你女朋友而委曲求全的和spring boot mybatis假意相处。和

    2023年04月21日
    浏览(24)
  • springboot3 集成mybatis 和通用mapper

    xml版本查看:https://www.cnblogs.com/binz/p/6564490.html springboot3.x以前的版本查看 https://www.cnblogs.com/binz/p/17421063.html springboot3.x查看  https://www.cnblogs.com/binz/p/17654403.html 1、pom引用 !-- openapi、 swagger3、knife4j配置,适用boot3 -- !-- https://doc.xiaominfo.com -- dependency groupId com.github.xiaoymin/ groupI

    2024年02月11日
    浏览(34)
  • SpringBoot第24讲:SpringBoot集成MySQL - MyBatis XML方式

    上文介绍了用JPA方式的集成MySQL数据库,JPA方式在中国以外地区开发而言基本是标配, 在国内MyBatis及其延伸框架较为主流 。本文是SpringBoot第24讲,主要介绍 MyBatis技栈的演化 以及 SpringBoot集成基础的MyBatis XML实现方式 的实例。

    2024年02月15日
    浏览(26)
  • SpringBoot第26讲:SpringBoot集成MySQL - MyBatis PageHelper分页

    前文中,我们展示了Spring Boot与MyBatis的集成,但是没有展示分页实现。本文是SpringBoot第26讲,专门介绍分页相关知识体系和基于MyBatis的 物理分页PageHelper

    2024年02月13日
    浏览(31)
  • SpringBoot 集成MyBatis-Plus-Generator(最新版3.5.2版本)自动生成代码(附带集成MyBatis-Plus)

    快速入门 代码生成器配置(新) spring boot 2.3.12.RELEASE mybatis 3.5.2 mybatis plus 3.5.2 mybatis plus generator 3.5.2 mysql 8.0.17 velocity 2.3 hutool 5.8.15 druid 1.2.8 lombok 自带 示例程序选择的技术目前各项技术的稳定版本。 相信大家厌烦重复的造轮子过程,编写与数据库表对应的实体类,接着再进

    2024年02月21日
    浏览(42)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包