初步
-
创建一个springboot的项目,记得加入mybatis-plus依赖,(阿里巴巴的有这个start,直接点击就可以,狂况且速度快,https://start.aliyun.com)
-
手动添加druid数据库连接池的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
- 配置yaml配置文件
# 数据库连接四大参数,以及数据库连接池
spring:
datasource:
url: jdbc:mysql://localhost:3306/***?serverTimezone=UTC
username: root
password: ***
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
mybatis-plus:
configuration:
#输出到控制台的日志方式
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
# mybatis的配置文件存放路径,可以不用
#config-location: classpath:mybatis-config.xml
#mapper配置文件存放的路径,记得在resource目录下添加mybatis文件夹
mapper-locations: classpath*:mybatis/*.xml
type-aliases-package: com.laixi.pojo
global-config:
db-config:
# 全局id自动增长,mybatis-plus内部不是自动增长的需要手动设置
id-type: auto
table-prefix: tb_
分页配置
在springboot启动类的同一目录下建立一个config包,创建下面的类
官网链接
public class MybatisPlusConfig {
// 最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
}
实体类的一些基本注解
//当数据库中表名与实体类名不同时,可以用这个注解来指定数据库表明名称,当然假如只是单纯的缺少前缀可以在总的配置文件中来解决
@TableName("tb_user")
//在数据库中不存在的数据,建议加上这个注解,不然在分页查询可能出现错误,Unknown column 'error' in 'field list'
@TableField(exist = false)
//解决数据库与javabean中数据不一致问题
@TableField(value = "email")
private String mail;
继承BaseMapper
@Mapper
public interface UserMapper extends BaseMapper<User> {}
现在只需要 @Autowired UserMapper 就可以使用了
增删改查
补充插件
MyBstisX 是Idea中的一个针对mybatis-plus的插件,可以实现快速在mapper接口和xml之间的跳转