软件:idea 然后用spring boot 数据库用的postgersql
在谈mybatis-plus之前,我先说一个开发中非常好用的插件吧。用了这款插件之后,开发起来,会快很多。他就是 ----- > Mybatis plugins我这是安装好了的,没安装好之前是install,直接点就可以了。
下面开始我们今天的主题:mybatis-plus
首先先导入jar包
com.baomidou
mybatis-plus-boot-starter
3.0.1
com.baomidou
mybatisplus-spring-boot-starter
1.0.5
org.apache.velocity
velocity-engine-core
2.0
然后在配置文件中配置数据源
# Tomcat
server:
tomcat:
uri-encoding: UTF-8
max-threads: 1000
min-spare-threads: 30
port: 8880
spring:
application:
name: userinfo_plus
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: org.postgresql.Driver
druid:
url: jdbc:postgresql://xx.xx.xx.xx/项目名
username: postgres
password: postgres
initial-size: 10
max-active: 100
min-idle: 10
max-wait: 60000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1
test-while-idle: true
test-on-borrow: false
test-on-return: false
stat-view-servlet:
enabled: true
url-pattern: /druid/*
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true
mybatis:
mapperLocations: classpath:mybatis/mapping/**/*.xml
config-location: classpath:mybatis/mybatis-config.xml
#逻辑删除的状态
mybatis-plus:
global-config:
db-config:
logic-delete-value: 1
logic-not-delete-value: 0
数据源配置好之后新建一个包generator然后在其中新建一个类CodeGenerator(这个随便自己)自动生成,超级方便。
然后运行输入你的表名,就会自动生成相应的mapper层,server层,controller层等等
下面说的是个人习惯:
将mapper层中加入Mapper注解(这个注解可以不加,在启动类中加入@MapperScan("com.example.demo.mapper")也可以),controller层加入RestController注解。然后就可以写业务了,非常的舒服。这是一个controller的一个例子
entity层的话,可以继承下Model类,然后重写pkVal方法这里面的注解什么的在下面解释下。
一。 如果你的删除是逻辑删除,就在你的状态上加上@TableLogic注解,
然后在你的config中注入
@Bean
public LogicSqlInjector logicSqlInjector(){
return new LogicSqlInjector() ;
}
二。如果业务需要加上乐观锁,只需要在你的版本号字段上面加上@Version注解,和jpa一样方便。
然后在你的config中注入
//乐观锁(目前只支持updateById和update方法)
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
三。 分页也需要注入,不注入也可以分页吧,不过不是数据库分页,你可以看生成的sql语句就知道了。
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
@TableField注解 表示要和数据库的名字一样
@TableField( "update_time")
private LocalDateTime updateTime;
@TableId(type = IdType.AUTO) //表示mysql的自增,我用的是postgresql,所以没有试过。
@TableField(condition = SqlCondition.LIKE)//模糊查询,不设置的话会默认。