1.导入pom依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
2.配置application.yml
spring:
server:
port: 8888
datasource:
username: root
password: root
url: jdbc:mysql://localhost:33060/mybatis_plus?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
profiles:
active: dev # 设置项目的开发环境
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 设置日志为控制台输出
# 配置逻辑删除
global-config:
db-config:
logic-delete-value: 1 # 删除的值为1
logic-not-delete-value: 0 # 不删除的值为0
3.编写MybatisPlusConfig配置类
包含:分页插件,乐观锁插件,逻辑删除,SQL执行效率插件
@Configuration //配置类
@MapperScan("com.kuang.mapper") //扫描mapper包
@EnableTransactionManagement //开启事务
public class MybatisPlusConfig {
//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
//逻辑删除
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
//SQL执行效率插件
@Bean
@Profile({"dev","test"})// 设置 dev test 环境开启
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(1000); //单位ms,设置最大执行时间,超时则不执行
performanceInterceptor.setFormat(true); //格式化SQL
return performanceInterceptor;
}
}
3.编写实体类
public class User {
@TableId(type = IdType.INPUT) //对应数据库中的自增 默认为ID_WORKER, 全局唯一,雪花算法
private Long id;
private String name;
private Integer age;
private String email;
@TableLogic //逻辑删除
private Integer deleted;
@Version //乐观锁version注解
private Integer version;
//字段添加填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
4.编写填充策略类(自动填充数据表中的属性)
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
//插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
//更新时的填充策略
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
5.编写mapper类(继承BaseMapper就完事了)
@Repository
public interface UserMapper extends BaseMapper<User> {
}
6,结束了,可以用了
下面mybatis-plus的常用方法
1.mapper类中常用方法
//查询全部
userMapper.selectList(null);
//根据id查询
userMapper.selectById(1l);
//批量查询
userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
//分页查询
Page<User> userPage = new Page<>(1,5);
IPage<User> page = userMapper.selectPage(userPage, null);
//插入
userMapper.insert(user);
//更新
userMapper.update(user, null);
userMapper.updateById(user);
//根据map删除
HashMap<String, Object> map = new HashMap<>();
map.put("name","张三");
userMapper.deleteByMap(map);
//删除
userMapper.deleteById(6l); //配置逻辑删除后,删除操作为更新语句,将deleted更新为1
2.条件查询,wrapper
//查询email,name不为空,年龄大于18的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("email")
.isNotNull("name")
.ge("age", 18); //年龄>=18
userMapper.selectList(wrapper).forEach(System.out::println);
//查询名字为Tom的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "Tom");
User user = userMapper.selectOne(wrapper);
System.out.println(user);
//查询年龄在18,22之间的用户,根据id排序
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.between("age", 18, 22)
.orderByDesc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
//直接写SQL查询
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.inSql("id","select id from user where id < 4");
userMapper.selectObjs(wrapper).forEach(System.out::println);
3.mybatis-plus代码自动生成工具类
public class MysqlGenerator {
public static void main(String[] args) {
//代码自动生成器对象
AutoGenerator generator = new AutoGenerator();
//1.全局配置
GlobalConfig gc = new GlobalConfig();
String path = System.getProperty("user.dir"); //获取到项目根目录
gc.setOutputDir(path+"/src/main/java"); //输出目录
gc.setAuthor("cdd"); //设置作者
gc.setOpen(true); //完成后打开文件夹
gc.setFileOverride(false); //是否覆盖
// gc.setServiceName("%sService"); //去service的I前缀
gc.setIdType(IdType.INPUT); //设置而id的手动输入
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true); //支持swagger
generator.setGlobalConfig(gc);
//2.设置数据源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:33060/mybatis_plus?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setDbType(DbType.MYSQL);
generator.setDataSource(dsc);
//3.包的配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("mybatis_plus");
pc.setParent("com.kuang");
pc.setEntity("pojo");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
generator.setPackageInfo(pc);
//4.策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user"); //设置要映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true); //自动lombok
strategy.setLogicDeleteFieldName("deleted"); //逻辑删除字段
//自动填充
TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(createTime);
tableFills.add(updateTime);
strategy.setTableFillList(tableFills);
//乐观锁
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2 url采用下划线风格
generator.setStrategy(strategy);
generator.execute();
}
}