上一篇文章给大家讲了怎么用idea社区版创建spring boot项目,今天给大家写一下如何用spring boot 整合mybatis-plus,过程很简单。之后再给大家展开为什么用mybatis-plus,而不直接用jdbc,简单说一下,其实大数据项目,都是用jdbc,而不用orm框架,因为框架中的事务管理和执行过程中调用反射api都会影响性能。小项目无所谓了,怎么开发快怎么来。好了废话不多说直接上代码。
一、pom.xml添加依赖
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.5.2
com.example
demo
0.0.1-SNAPSHOT
demo
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
com.baomidou
mybatis-plus-boot-starter
3.4.0
com.baomidou
mybatis-plus-generator
3.4.0
org.apache.velocity
velocity
1.7
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
src/main/resources
true
src/main/java
**/*.xml
src/main/resources
**/*
注意上面在build节点我添加了resources节点,因为我习惯不把mybatis的xml文件放在项目的resource下,所以在pom中添加了resources节点才能把xml打到jar包中。
二、application.yml如下:
server:
port: 5211
servlet:
context-path: /demo
spring:
application:
name: demo
jmx:
default-domain: demo
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
datasource:
url: jdbc:mysql://192.168.16.130:3306/demo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
pool-name: demo
minimum-idle: 5
idle-timeout: 120000
max-lifetime: 120000
maximum-pool-size: 30
connection-timeout: 6000
connection-test-query: select 1
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
mapper-locations: classpath:com/example/demo/mapper/*.xml
分页插件
@Configuration
public class MybatisPlusConfig {
/**
* 分页插件
* 最新版,不用担心最大数限制
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
代码自定生成类
package com.example.demo.generator;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class Generator {
public void generateCode(String tableName) {
// 指定包名
String packageName = "com.example.demo";
// user -> UserService, 设置成true: user -> IUserService
boolean serviceNameStartWithI = false;
// 指定生成的表名
String[] tableNames = new String[]{tableName};
generateByTables(serviceNameStartWithI, packageName, tableNames);
}
/**
* 根据表自动生成
*
* @param serviceNameStartWithI 默认为false
* @param packageName 包名
* @param tableNames 表名
* @author Terry
*/
private void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) {
// 配置数据源
DataSourceConfig dataSourceConfig = getDataSourceConfig();
// 策略配置
StrategyConfig strategyConfig = getStrategyConfig(tableNames);
// 全局变量配置
GlobalConfig globalConfig = getGlobalConfig(serviceNameStartWithI);
// 包名配置
PackageConfig packageConfig = getPackageConfig(packageName);
// 自动生成
atuoGenerator(dataSourceConfig, strategyConfig, globalConfig, packageConfig);
}
/**
* 集成
*
* @param dataSourceConfig 配置数据源
* @param strategyConfig 策略配置
* @param config 全局变量配置
* @param packageConfig 包名配置
* @author Terry
*/
private void atuoGenerator(DataSourceConfig dataSourceConfig, StrategyConfig strategyConfig, GlobalConfig config,
PackageConfig packageConfig) {
new AutoGenerator().setGlobalConfig(config).setDataSource(dataSourceConfig).setStrategy(strategyConfig)
.setPackageInfo(packageConfig).execute();
}
/**
* 设置包名
*
* @param packageName 父路径包名
* @return PackageConfig 包名配置
* @author Terry
*/
private PackageConfig getPackageConfig(String packageName) {
return new PackageConfig().setParent(packageName).setXml("mapper").setMapper("dao").setController("controller")
.setEntity("entity");
}
/**
* 全局配置
*
* @param serviceNameStartWithI false
* @return GlobalConfig
* @author Terry
*/
private GlobalConfig getGlobalConfig(boolean serviceNameStartWithI) {
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setBaseColumnList(true).setBaseResultMap(true).setActiveRecord(false).setAuthor("ligang")
// 设置输出路径
.setOutputDir(getOutputDir("demo")).setFileOverride(true);
if (!serviceNameStartWithI) {
// 设置service名
globalConfig.setServiceName("%sService");
}
return globalConfig;
}
/**
* 返回项目路径
*
* @param projectName 项目名
* @return 项目路径
* @author Terry
*/
private String getOutputDir(String projectName) {
String path = this.getClass().getClassLoader().getResource("").getPath();
int index = path.indexOf(projectName);
return path.substring(1, index) + projectName + "/src/main/java/";
}
/**
* 策略配置
*
* @param tableNames 表名
* @return StrategyConfig
* @author Terry
*/
private StrategyConfig getStrategyConfig(String... tableNames) {
return new StrategyConfig()
// 全局大写命名 ORACLE 注意
.setCapitalMode(true).setEntityLombokModel(false)
// 从数据库表到文件的命名策略
.setNaming(NamingStrategy.underline_to_camel)
// // 需要生成的的表名,多个表名传数组
.setInclude(tableNames);
}
/**
* 配置数据源
*
* @return 数据源配置 DataSourceConfig
* @author Terry
*/
private DataSourceConfig getDataSourceConfig() {
String dbUrl = "jdbc:mysql://192.168.16.132:3306/demo?useSSL=false";
return new DataSourceConfig().setDbType(DbType.MYSQL).setUrl(dbUrl).setUsername("root")
.setPassword("summer123").setDriverName("com.mysql.cj.jdbc.Driver");
}
/**
* 根据表自动生成
*
* @param packageName 包名
* @param tableNames 表名
* @author Terry
*/
@SuppressWarnings("unused")
private void generateByTables(String packageName, String... tableNames) {
generateByTables(true, packageName, tableNames);
}
public static void main(String[] args) {
new Generator().generateCode("demo");
}
}
添加测试表
CREATE TABLE `demo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`sex` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
在启动类中添加@MapperScan注解,参数是我们dao接口的目录
@SpringBootApplication
@MapperScan("com.example.demo.dao")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
执行generator的main方法,即可自动创建出对应的 model、mapper、dao、service、serviceimpl、 controller。本篇不展开讲自动生成工具
public class Demo implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
private String sex;
private Integer age;
}
创建dao接口
public interface DemoMapper extends BaseMapper {
}
创建service
public interface DemoService extends IService {
}
创建service的实现
@Service
public class DemoServiceImpl extends ServiceImpl implements DemoService {
}
下面是mybatis-plus为我们封装好了一些通用方法,大家可以自己去试试,有问题在下方留言。
// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection entityList);
// 插入(批量)
boolean saveBatch(Collection entityList, int batchSize);
// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection entityList, int batchSize);
// 根据 entity 条件,删除记录
boolean remove(Wrapper queryWrapper);
// 根据 ID 删除
boolean removeById(Serializable id);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection extends Serializable> idList);
// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper updateWrapper);
// 根据 whereWrapper 条件,更新记录
boolean update(T updateEntity, Wrapper whereWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection entityList, int batchSize);
// 根据 ID 查询
T getById(Serializable id);
// 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
T getOne(Wrapper queryWrapper);
// 根据 Wrapper,查询一条记录
T getOne(Wrapper queryWrapper, boolean throwEx);
// 根据 Wrapper,查询一条记录
Map getMap(Wrapper queryWrapper);
// 根据 Wrapper,查询一条记录
V getObj(Wrapper queryWrapper, Function super Object, V> mapper);
// 查询所有
List list();
// 查询列表
List list(Wrapper queryWrapper);
// 查询(根据ID 批量查询)
Collection listByIds(Collection extends Serializable> idList);
// 查询(根据 columnMap 条件)
Collection listByMap(Map columnMap);
// 查询所有列表
List
以上spring boot 整合mybatis-plus的初级篇就写完了,接下来我们会展开讲mybatis-generator和mybatis-plus的QueryWrapper还有mybatis-plus的多数据源,会分成三篇来讲。谢谢大家点赞关注。