mybatis-plus
是一个mybatis的插件,是国内开发的,还没有进入springboot的孵化器,加入了mybatis-plus的依赖,就不要再加mybatis依赖。
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
lombok插件
在实体类上加入@Data注解,可以自动生成set,get方法和构造方法,只需要写属性即可
数据库的配置信息
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&
username: root
password: 321
#此配置可以将sql语句打印在日志中,它实现了了Log接口
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
使用mp
将操作数据库的mapper文件继承BaseMapper<实体类名>
public interface UserMapper extends BaseMapper<User>{
}
此接口在项目运行过程中会动态创建sql语句,无法查看
注解
@Data
@TableName(value="user")//如果表名为user,可以使用此注解映射
public class Teacher{
@TableId(value="id")//映射主键字段名
private Integer num;
@TableField("TableField")//映射非主键字段名
private String username;
private Integer age;
}
常用注解1、@TableName(value=“user”)
作用:如果通过实体类名无法找到该表,可以使用该注解来映射该表名
位置:在实体类上加此注解
常用注解2、@TableField(value=“name”)
作用:映射某个非主键字段名
参数 | 作用 |
---|---|
value | 字段名 |
exist | 是否存数据库(默认为 true) |
select | 是否查询该字段(默认为true) |
fill = FieldFill.INSERT_UPDATE | 存的时候mp自动赋值,比如create_time,update_time |
位置:在实体类的属性上加
fill
public class User {
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
@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);
}
}
常用注解3、@TableId(value=“id”)
作用:映射主键
参数:value为主键字段名,type设置主键类型,主键的生成策略
type值 | 描述 |
---|---|
IdType.AUTO | 数据库自增 |
IdType.NONE(默认) | MP自动set主键,雪花算法实现,主键必须为Long,int长度不够 |
IdType.INPUT | 需要开发者手动赋值,如果传入了null,数据库通过自增赋值 |
IdType.ASSING_ID | MP分配ID,可以用Long、Integer、String |
IdType.ASSING_UUID | 分配UUID,主键只能用String |
@Deprecated(不推荐使用)
IdType.ID_WORDKER(3)
IdType.ID_WORKER_STR(3)
IdType.UUID(4)
位置:在实体类的主键上加
@Version
标记乐观锁,通过version字段来保证数据的安全性,当修改该条数据的时候,会检验version,操作成功后会将version字段自增1,所以同时只能修改一次
update ...set version = 2 where version = 1
、
1、增加version字段
public class User{
@Version
private Integer version;
}
2、添加配置类
@Configuration
public class MyBatisPlusConfig {
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return optimisticLockerInterceptor();
}
}
EnumValue
用枚举类注解,将数据库字段映射成枚举类型
第一种方式:注解
1、创建枚举类
public enum StatusEnum {
WORK(1,"上班"),
REST(0,"休息");
StatusEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
@EnumValue
private Integer code;
private String msg;
}
2、在实体类添加字段名
private StatusEnum status;//成员变量一定要和枚举字段名字对应
3、配置文件中添加枚举包扫描
type-enums-package: cn.qzj.enums
第二种方式:实现接口
创建枚举类
public enum AgeEnum implements IEnum<Integer> {
CHIlD(1,"未成年"),
ADULT(0,"18周岁以上");
private Integer code;
private String msg;
AgeEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
@Override
public Integer getValue() {
return code;
}
}
2、在实体类添加字段名
private AgeEnum age;//成员变量一定要和枚举字段名字对应
3、配置文件中添加枚举包扫描
TableLogic
映射逻辑删除(假删)
1、数据库添加deleted字段
2、实体类添加注解
@TableLogic
private Integer deleted;
3、在配置文件中加如下配置
mybatis-plus:
global-config:
db-config:
logic-delete-value: 1
logic-not-delete-value: 0
select方法
@Autowired
private UserMapper mapper;
@Test
void test(){
mapper.selectList(null);//不加任何条件全部查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("name","张三");//name=张三
Map<String,Object> map = new HashMap<>();
map.put("name","张三");
map.put("age",1);
wrapper.allEq(map); //name="张三"并且age = 1
wrapper.lt("age",20);//age<20
wrapper.gt("age",20);//age>20,
wrapper.ge("age",20);//age>=20,
wrapper.ne("name","李四");//name!= 李四
wrapper.like("name","a");//like "%a%"
wrapper.likeLeft("name","a");//like '%a'
wrapper.likeRight("name","a");//like 'a%'
//联合查询(IN)
wrapper.inSql("id","select id from user where id <10");
wrapper.inSql("age","select age from user where age >20")
//排序
warpper.orderByAsc("age");//升序
warpper.orderByDesc("age");//降序
wrapper.having("id > 8");//按照id大于8的数据 按照age降序
mapper.selectList(wrapper);
mapper.selectById(8);//根据id查询
mapper.selectBatchIds(Arrays.asList(1,2,4));//根据多个id查询
Map<String,Obejct> map = new HashMap<>();
map.put("id",7);
mapper.selectByMap(map);//map只能做等于判断,逻辑需要Wrapper
wrapper.gt("id",1);//id>1
mapper.selectCount(wrapper);//返回查到的数据数量
mapper.selectMaps(wrapper);//将查询的结果集封装到Map集合里
mapper.selectObjs(null);//返回所有的id
wapper.eq("id",1)
mapper.selectOne(wapper);//返回一条数据
}
分页查询
1、在配置类中加入拦截器
@Configuration
public class MyBatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
2、
@Autowired
private UserMapper mapper;
@Test
void test(){
QueryWrapper wrapper = new QueryWrapper();
Page<user> page = new Page<>(1,2);//第一页,每页两条
Page<user> result = mapper.selectPage(page,null);//返回Page对象,不按任何条件查询
result.getSize();//每页的条数
result.getTotal();//总纪录数
result.getRecords();//结果
/*
records 用来存放查询出来的数据
total 返回记录的总数
size 每页显示条数,默认 10
current 当前页,默认1
orders 排序字段信息
optimizeCountSql 自动优化 COUNT SQL,默认true
isSearchCount 是否进行 count 查询,默认true
hitCount 是否命中count缓存,默认false
*/
Page<Map<String,Object>> page = new Page<>(1,2);//第一页,每页两条
mapper.selectMapsPage(page,null);//将结果集封装到map集合里
自定义SQL(多表关联查询)
student表
teacher表
select语句
select * from teacher t,student s where t.user_id = s.id and t.user_id = 2;
在mapper文件中自定义方法
public interface UserMapper extends BaseMapper<User> {
//自定义方法
@Select("select * from teacher t,student s where t.user_id = s.id and t.user_id = #{id}")
List<Teacher> teacherList(Integer id);
}
增删改
//直接插入user对象
mapper.insert(user);
//根据wrapper修改
userMapper.update(user,wrapper);
//根据user的id修改
userMapper.updateById(user);
//根据wrapper删除
userMapper.delete(wrapper);
//根据某个id删除
userMapper.deleteById(1);
//根据map储存的条件删除
userMapper.deleteByMap(map);
//根据id集合删除
userMapper.deleteBatchIds(idList);
主键自增插入数据时获取主键值
Mybatis获取主键值
<insert useGeneratedKeys="true" keyProperty="id">
insert into t_....;
</insert>
mp自动获取获取
mapper.insert(blog);
blog.getId();
MyBatis Plus自动生成
根据数据表自动生成实体类、Mapper、Service、ServiceImpl、Controller
1、在pom中导入Mybatis Plue Generator
</dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
三种模板:velocity(默认)、Freemarker、Beetl
配置
package cn.qzj;
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;
/**
* Create by qzj on 2021/01/10 16:38
**/
public class Main {
public static void main(String[] args) {
//创建generator对象
AutoGenerator autoGenerator = new AutoGenerator();
//数据源
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL);
dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("321");
autoGenerator.setDataSource(dataSourceConfig);
//全局配置
GlobalConfig globalConfig = new GlobalConfig();
//生成类的位置,从绝对路径开始
globalConfig.setOutputDir(System.getProperty("user.dir")+"/ch07-springboot-mp-test/src/main/java");
//false,创建好之后不会打开文件夹
globalConfig.setOpen(false);
//创建作者名
globalConfig.setAuthor("qiuzhijun");
autoGenerator.setGlobalConfig(globalConfig);
//包信息
PackageConfig packageConfig = new PackageConfig();
//父包
packageConfig.setParent("cn.qzj.mybatisplus");
//创建新的包,会在这个包里放所有生成的东西
packageConfig.setModuleName("generator");
packageConfig.setController("controller");
packageConfig.setService("service");
packageConfig.setServiceImpl("serviceImpl");
packageConfig.setMapper("mapper");
packageConfig.setEntity("entity");
autoGenerator.setPackageInfo(packageConfig);
//配置策略
StrategyConfig strategyConfig = new StrategyConfig();
//创建好实体类后自动添加@Data注解
strategyConfig.setEntityLombokModel(true);
//按照下划线转驼峰
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
autoGenerator.setStrategy(strategyConfig);
//执行
autoGenerator.execute();
}
}