springboot集成mybatisPlus
一 前言
mybatisPlus 能够简化开发,减少重复代码,很不错的一个项目!!
二 springboot 集成 mybatisPlus
2.1准备工作
建表语句
CREATE TABLE `customer` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`customer_name` varchar(255) DEFAULT NULL COMMENT '顾客名称',
`gender` varchar(255) DEFAULT NULL COMMENT '性别',
`telephone` varchar(255) DEFAULT NULL COMMENT '电话号码',
`register_time` timestamp NULL DEFAULT NULL COMMENT '注册时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8 COMMENT='顾客表';
项目依赖
<dependencies>
<!-- -->
<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>
<scope>test</scope>
</dependency>
<!-- mybaits plus 插件 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!-- 阿里数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok简化代码 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
2.2 配置文件
看 mybatis-plus相关配置; 关键点是 全局 id 的配置;
- 主键类型 0:"数据库ID自增";
- 1:"用户输入ID";
- 2:"全局唯一ID (数字类型唯一ID)";
- 3:"全局唯一ID UUID";
# 配置端口
server:
port: 8085
servlet:
context-path: /zszxz
application-display-name: mybatis-plus-demo
spring:
application:
name: mybatis-plus-demo
# 配置数据源
datasource:
url: jdbc:mysql://127.0.0.1:3306/zszxz?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false
username: root
password:
driver-class-name: com.mysql.jdbc.Driver
druid:
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select '1'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
# mybatis-plus相关配置
mybatis-plus:
# xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
mapper-locations: classpath:**/*Mapper.xml
# 以下配置均有默认值,可以不设置
global-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: 0
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: 2
#驼峰下划线转换
db-column-underline: true
#刷新mapper 调试神器
refresh-mapper: false
#数据库大写下划线转换
#capital-mode: true
#序列接口实现类配置
#key-generator: com.baomidou.springboot.xxx
#逻辑删除配置
#logic-delete-value: 0 # 逻辑已删除值(默认为 1)
#logic-not-delete-value: 1 # 逻辑未删除值(默认为 0)
#自定义填充策略接口实现
# meta-object-handler: com.zhengqing.config.MyMetaObjectHandler
#自定义SQL注入器
#sql-injector: com.baomidou.springboot.xxx
configuration:
# 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射
map-underscore-to-camel-case: true
cache-enabled: false
# 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段
# call-setters-on-nulls: true
# 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 解决oracle更新数据为null时无法转换报错,mysql不会出现此情况
jdbc-type-for-null: 'null'
2.3 实体
- @TableName 映射数据库表名
- @TableId 对应主键类型,局部配置;
- @TableField 注解对应数据库字段
/**
* @Author lsc
* <p> </p>
*/
@Data
@TableName("customer")// 映射数据库表名
public class Customer {
//主键
@TableId(type = IdType.AUTO)
private Long id;
// 如果字段和数据库列对应可省略该注解
// @TableField(value = "NAME",exist = true)
private String customerName;
private String gender;
private String telephone;
private String registerTime;
}
2.4 mapper
mapper 多了继承 BaseMapper
/**
* @Author lsc
* <p> </p>
*/
@Repository
@Mapper
public interface CustomerMapper extends BaseMapper<Customer> {
}
2.5 映射文件
与普通的mybatis映射文件一样;如果要使用原生的Mybatis 方法,自定义即可,跟原来没区别;
<?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" >
<mapper namespace="com.zszxz.plus.mapper.CustomerMapper">
</mapper>
2.6 分页配置
分页
/**
* @Author lsc
* <p> </p>
*/
@Configuration
@MapperScan("com.zszxz.plus.service.*.mapper*")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
return paginationInterceptor;
}
}
2.7 启动类
@SpringBootApplication
// 扫描mapper文件
@MapperScan("com.zszxz.plus.mapper")
public class SpringbootMybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisPlusApplication.class, args);
}
}
2.8测试
集成 mybatis plus 后 会有一些默认 的crud方法, 简化开发;
@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringbootMybatisPlusApplicationTests {
@Autowired
CustomerMapper customerMapper;
@Test
public void add() {
Customer customer = new Customer();
customer.setCustomerName("大牛");
customer.setGender("男");
customer.setTelephone("66566");
customerMapper.insert(customer);
}
@Test
public void update() {
Customer customer = new Customer();
customer.setId(26L);
customer.setCustomerName("大牛哥");
customer.setGender("男");
customer.setTelephone("66566");
customerMapper.updateById(customer);
}
@Test
public void delete() {
customerMapper.deleteById(24L);
}
@Test
public void selectByid() {
Customer customer = customerMapper.selectById(26L);
// Customer(id=26, customerName=大牛哥, gender=男, telephone=66566, registerTime=null)
System.out.println(customer);
}
@Test
public void selectByWrapper() {
// 条件封装
QueryWrapper<Customer> wrapper = new QueryWrapper<>();
wrapper.eq("id",26L);
List<Customer> customers = customerMapper.selectList(wrapper);
// [Customer(id=26, customerName=大牛哥, gender=男, telephone=66566, registerTime=null)]
System.out.println(customers);
}
@Test
public void page() {
Page<Customer> page = new Page<>(1, 2);
IPage<Customer> customerIPage = customerMapper.selectPage(page, null);
System.out.println(customerIPage);
}
}
更多内容参照官网
本套教程
- springboot入门 (1)
- Springboot自定义banner(2)
- springboot配置文件解析(3)
- springboot集成mybatis(4)
- springboot集成jdbcTemplate(5)
- spingboot单元测试(6)
- springboot集成thymeleaf(7)
- springboot多文件上传(8)
- springboot文件下载(9)
- Springboot自定义异常类(10)
- springboot多环境配置(11)
- springboot自动配置原理解析(12)
- springboot集成restTemplate接口调用(13)
- springboot集成任务调度(14)
- springboot跨域CORS处理(15)
- springboot开启GIZP压缩(16)
- springboot集成logback(17)
- springboot集成Swagger(18)
- springboot集成actuator后台监控(19)
- springboot集成mybatis+oracle+druid(20)
- springboot 集成springsession(21)
- springboot集成jwt(22)
- springboot集成admin后台监控(23)
- springboot集成redis基础篇(24)
- springboot集成redis缓存篇(25)
- springboot使用AOP日志拦截(26)
- springboot集成Validation参数校验(27)
- springboot集成mybatisPlus(28)
- springboot集成shiro(29)
- springboot实现接口等幂次校验(30)
- springboot-集成WebSockets(31)
- restTemplate源码解析(32)
- SpringBoot使用@Async异步调用与线程池(33)
- 待续