整合 mybatis-plus
添加依赖
<dependency>
<groupId>com.litongjava</groupId>
<artifactId>tio-boot</artifactId>
<version>${tio.boot.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok-version}</version>
<optional>true</optional>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>4.0.3</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!--mybatis-plus 无需spring依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.1.1</version>
<exclusions>
<exclusion>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
初始化测试数据
创建数据库
CREATE DATABASE mybatis_plus_study DEFAULT CHARACTER SET utf8
创建表
CREATE TABLE USER(
id BIGINT(20) NOT NULL COMMENT '主键ID',
NAME VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
addr VARCHAR(250) NULL DEFAULT NULL COMMENT '地址',
remark VARCHAR(250) NULL DEFAULT NULL COMMENT '备注',
PRIMARY KEY (id)
)
随便插入几条条记录
INSERT INTO USER (id, NAME, age, email, addr, remark) VALUES (1, '张三', 25, 'zhangsan@example.com', '北京市朝阳区', '无');
INSERT INTO USER (id, NAME, age, email, addr, remark) VALUES (2, '李四', 30, 'lisi@example.com', '上海市浦东新区', '无');
INSERT INTO USER (id, NAME, age, email, addr, remark) VALUES (3, '王五', 35, 'wangwu@example.com', '广州市天河区', '无');
添加实体类和 Mapper
添加配置文件 mybatis.xml
package demo.mybatis.plus.model;
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private int age;
private String email;
private String addr;
private String remark;
}
package demo.mybatis.plus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import demo.mybatis.plus.model.User;
public interface UserMapper extends BaseMapper<User> {
}
使用工具类类整合 mybatis-plus
添加配置文件 mybatis.xml
- 数据源配置
- mapper 配置
<?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>
<environments default="default">
<environment id="default">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://192.168.3.9:3306/mybatis_plus_study" />
<property name="username" value="root" />
<property name="password" value="robot_123456#" />
</dataSource>
</environment>
</environments>
<mappers>
<package name="demo.mybatis.plus.mapper" />
</mappers>
</configuration>
MybatisPlusUtils
- 使用 MybatisSqlSessionFactoryBuilder 初始化 mybaits,初始化完成后会自动创建 MapperStatement
package demo.mybatis.plus.utils;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MybatisPlusUtils {
public static final String resource = "mybatis.xml";
private static SqlSessionFactory factory;
static {
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
// factory= new SqlSessionFactoryBuilder().build(inputStream);
MybatisSqlSessionFactoryBuilder builder = new MybatisSqlSessionFactoryBuilder();
log.info("builder:{}", builder);
factory = builder.build(inputStream);
log.info("factory:{}", factory);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
/**
* 返回factory
* @return
*/
public static SqlSessionFactory getFactory() {
return factory;
}
/**
* 打开会话
* @return
*/
public static SqlSession openSession(boolean autoCommit) {
return factory.openSession(autoCommit);
}
public static SqlSession openSession() {
return factory.openSession(true);
}
}
使用 Controller 和 Service 测试
package demo.mybatis.plus.services;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import demo.mybatis.plus.mapper.UserMapper;
import demo.mybatis.plus.model.User;
import demo.mybatis.plus.utils.MybatisPlusUtils;
import lombok.extern.slf4j.Slf4j;
/**
* @author create by Ping E Lee on 2022年3月28日 下午6:12:10
*
*/
@Slf4j
public class UserServcie {
public List<User> selectList() {
try (SqlSession sqlSession = MybatisPlusUtils.openSession()) {
log.info("sqlSession:{}", sqlSession);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
log.info("userMapper:{}", userMapper);
return userMapper.selectList(null);
}
}
}
package demo.mybatis.plus.AController;
import java.util.List;
import com.litongjava.jfinal.aop.Inject;
import com.litongjava.annotation.RequestPath;
import demo.mybatis.plus.model.User;
import demo.mybatis.plus.services.UserServcie;
@RequestPath("/user")
public class UserController {
@Inject
private UserServcie userServcie;
public List<User> selectList() {
return userServcie.selectList();
}
}
工具类无配置文件 mybatis.xml 整合 mybatis-plus
下面介绍如何在不使用 mybatis.xml 配置文件的情况下整合 mybatis
添加 app.properties
jdbc.url=jdbc:mysql://192.168.3.9:3306/mybatis_plus_study
jdbc.user=root
jdbc.pswd=robot_123456#
修改 MybatisPlusUtils 如下
- 加速数据源
- 配置环境
- 添加 addMappers
- MybatisSqlSessionFactoryBuilder 构建出 SqlSessionFactory
package demo.mybatis.plus.utils;
import javax.sql.DataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import com.litongjava.tio.utils.environment.EnvUtils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MybatisPlusUtils {
private static SqlSessionFactory factory;
static {
String jdbcUrl = EnvUtils.get("jdbc.url");
String jdbcUser = EnvUtils.get("jdbc.user");
String jdbcPswd = EnvUtils.get("jdbc.pswd");
HikariConfig config = new HikariConfig();
// 设定基本参数
config.setJdbcUrl(jdbcUrl);
config.setUsername(jdbcUser);
config.setPassword(jdbcPswd);
config.setMaximumPoolSize(2);
DataSource dataSource = new HikariDataSource(config);
// environment
Environment environment = new Environment("default", new JdbcTransactionFactory(), dataSource);
// config
org.apache.ibatis.session.Configuration configuration = new MybatisConfiguration();
configuration.setEnvironment(environment);
configuration.addMappers("demo.mybatis.plus.mapper");
// MybatisSqlSessionFactoryBuilder
MybatisSqlSessionFactoryBuilder builder = new MybatisSqlSessionFactoryBuilder();
log.info("builder:{}", builder);
factory = builder.build(configuration);
}
/**
* 返回factory
* @return
*/
public static SqlSessionFactory getFactory() {
return factory;
}
/**
* 打开会话
* @return
*/
public static SqlSession openSession(boolean autoCommit) {
return factory.openSession(autoCommit);
}
public static SqlSession openSession() {
return factory.openSession(true);
}
}
使用配置类整合 mybatis-plus
DataSourceConfig 初始化配置源
package demo.mybatis.plus.config;
import javax.sql.DataSource;
import com.litongjava.jfinal.aop.annotation.Bean;
import com.litongjava.jfinal.aop.annotation.Configuration;
import com.litongjava.tio.utils.environment.EnvUtils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
@AConfiguration
public class DataSourceConfig {
@ABean(priority = 1)
public DataSource dataSource() {
String jdbcUrl = EnvUtils.get("jdbc.url");
String jdbcUser = EnvUtils.get("jdbc.user");
String jdbcPswd = EnvUtils.get("jdbc.pswd");
HikariConfig config = new HikariConfig();
// 设定基本参数
config.setJdbcUrl(jdbcUrl);
config.setUsername(jdbcUser);
config.setPassword(jdbcPswd);
config.setMaximumPoolSize(2);
return new HikariDataSource(config);
}
}
MybatisPlusConfig 配置 mybatis-plus
package com.litongjava.tio.web.hello.config;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import com.litongjava.jfinal.aop.annotation.AAutowired;
import com.litongjava.jfinal.aop.annotation.ABean;
import com.litongjava.jfinal.aop.annotation.AConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionManager;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import javax.sql.DataSource;
@Slf4j
@AConfiguration
public class MybatisPlusConfig {
@AAutowired
private DataSource dataSource;
/**
* 获取SqlSession
*
* @return
*/
@ABean(destroyMethod = "close")
public SqlSessionManager getSqlSession() {
// environment
Environment environment = new Environment("default", new JdbcTransactionFactory(), dataSource);
// MybatisConfiguration
org.apache.ibatis.session.Configuration configuration = new MybatisConfiguration();
configuration.setEnvironment(environment);
configuration.addMappers("demo.mybatis.plus.mapper");
// MybatisSqlSessionFactoryBuilder
MybatisSqlSessionFactoryBuilder builder = new MybatisSqlSessionFactoryBuilder();
log.info("builder:{}", builder);
SqlSessionFactory sqlSessionFactory = builder.build(configuration);
SqlSessionManager sqlSessionManager = SqlSessionManager.newInstance(sqlSessionFactory);
return sqlSessionManager;
}
}
在 service 和 controller 中调用测试
UserServcie
package demo.mybatis.plus.services;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionManager;
import com.litongjava.jfinal.aop.Autowired;
import demo.mybatis.plus.mapper.UserMapper;
import demo.mybatis.plus.model.User;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class UserServcie {
@AAutowired
private SqlSessionManager sqlSessionManager;
public List<User> selectList() {
try (SqlSession sqlSession = sqlSessionManager.openSession()) {
log.info("sqlSession:{}", sqlSession);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
log.info("userMapper:{}", userMapper);
return userMapper.selectList(null);
}
}
}
UserController
package demo.mybatis.plus.AController;
import java.util.List;
import com.litongjava.jfinal.aop.Inject;
import com.litongjava.annotation.RequestPath;
import demo.mybatis.plus.model.User;
import demo.mybatis.plus.services.UserServcie;
@RequestPath("/user")
public class UserController {
@Inject
private UserServcie userServcie;
public List<User> selectList() {
return userServcie.selectList();
}
}
使用 MybatisController 获取其他信息
package com.ppnt.jfinal.mybatis.plus.AController;
import java.util.Collection;
import org.apache.ibatis.binding.MapperRegistry;
import org.apache.ibatis.session.SqlSession;
import com.jfinal.core.AController;
import com.jfinal.core.Path;
import com.ppnt.jfinal.mybatis.plus.mapper.UserMapper;
import com.ppnt.jfinal.mybatis.plus.utils.MybatisPlusUtils;
import lombok.extern.slf4j.Slf4j;
@Path("mybatis")
@Slf4j
public class MybatisContoller extends Controller{
public void mappers() {
SqlSession sqlSession = MybatisPlusUtils.openSession();
MapperRegistry mapperRegistry = sqlSession.getConfiguration().getMapperRegistry();
Collection<Class<?>> mappers = mapperRegistry.getMappers();
for (Class<?> c : mappers) {
log.info("c:{}", c);
}
renderText("success");
}
public void getUserMapper() {
SqlSession sqlSession = MybatisPlusUtils.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
log.info("mapper:{}", mapper);
renderText("success");
}
}
测试访问地址 http://localhost/user/selectList http://localhost/mybatis/mappers http://localhost/mybatis/getUserMapper