主要是为了简化Mybatis的操作
在mybatis的基础上新增了插件,注入等功能
基本使用
1,创建个数据库表
id | name | age | |
---|---|---|---|
1 | Jone | 18 | test1@baomidou.com |
2 | Jack | 20 | test2@baomidou.com |
3 | Tom | 28 | test3@baomidou.com |
4 | Sandy | 21 | test4@baomidou.com |
5 | Billie | 24 | test5@baomidou.com |
2,创建一个空的Spring Boot工程
可以使用 Spring Initializer (opens new window)快速初始化一个 Spring Boot 工程
3,添加依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0+ 版本</version>
<relativePath/>
</parent>
引入 spring-boot-starter
、spring-boot-starter-test
、mybatis-plus-boot-starter
、h2
依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>最新版本</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
3,配置
在application.yml中配置文件中添加H2数据库的信息
# DataSource Config
spring:
datasource:
driver-class-name: org.h2.Driver
schema: classpath:db/schema-h2.sql
data: classpath:db/data-h2.sql
url: jdbc:h2:mem:test
username: root
password: test
在SpringBoot启动类中添加@MapperScan注解,,扫描Mapper文件夹
@SpringBootApplication
@MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
编码
编写实体类User.java(此处用了Lombok 简化了代码)
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
编写Mapper包下的UserMapper接口
public interface UserMapper extends BaseMapper<User> {
}
开始使用
添加测试类,进行功能测试
@SpringBootTest
public class SampleTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
Assert.assertEquals(5, userList.size());
userList.forEach(System.out::println);
}
}
提示
UserMapper中selectList()方法的参数为MP内置条件封装器,Wrapper,所以不用填写任何条件
通用的CRUD
插入操作
插入的主键idType属性,定义主键的生成策略
AUTO:使用数据库的自增策略
NONE/INPUT:自行输入主键
ASSIGN_ID:使用long属性储存雪花算法的值
ASSIGN_UUID:使用String类型储存雪花算法的值
TableField的一些属性
select:查询的时候是否被选中
exist:数据库中是否存在这个数据
value:设置column的名称
更新操作
根据ID进行更新(属性为null是不会更新的)
TbOrder order = tbOrderDao.selectById(1544929935098478593l);
order.setOname(null);
tbOrderDao.updateById(order);
根据条件更新
TbOrder order = new TbOrder();
order.setDetail("更新后的详情");
UpdateWrapper wrapper = new UpdateWrapper<>();
wrapper.eq("oname","订单2");
tbOrderDao.update(order,wrapper);
删除操作
根据ID删除
/**根据一个ID删除**/
tbOrderDao.deletById();
/**根据一组ID删除**/
tbOrderDao.deleteBatchIds();
根据Map删除
Map<String, Object> columnMap = new HashMap<>();
columnMap.put("age",29);
columnMap.put("name","梼杌");
//将columnMap中的元素设置为删除的条件,多个之间为and关系
int result = userMapper.deleteByMap(columnMap);
System.out.println("result = " + result);
根据Wrapper构造条件删除,可以实现or
QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
wrapper
.eq("oname","订单2")
.or()
.eq("detail","222");
tbOrderDao.delete(wrapper);
查询操作
根据ID进行查询
/**根据一个ID查询**/
heroMapper.selectById();
/**根据一组DI查询**/
hreoMapper.selectBatchIds();
根据Wrapper条件进行查询
QueryWrapper<HeroEntity> wrapper = new QueryWrapper<>();
wrapper.eq("hname","死歌");
HeroEntity heroEntity = heroMapper.selectOne(wrapper);
System.out.println(heroEntity.getHeroName()+":"+heroEntity.getHid());
分页查询
注册分页插件
@SpringBootApplication
public class MybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args);
}
@Bean
public MybatisPlusInterceptor paginationInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
}
实现分页操作
@Test
void testQueryPage(){
Page<HeroEntity> page = new Page<>(1,2);
heroMapper.selectPage(page,null);
System.out.println("总数:"+page.getTotal());
for (HeroEntity heroEntity :page.getRecords()) {
System.out.println(heroEntity.getHid()+":"+heroEntity.getHeroName());
}
}
Serivce接口的使用
创建继承了ISerivce接口的接口
public interface HeroService extends IService<HeroEntity> {
}
创建实现了Iserivce接口的Imp
@Service
public class HeroServiceImpl extends
ServiceImpl<HeroMapper, HeroEntity> implements HeroService {
}
通过已经实现的方式进行相关的操作
@Autowired
HeroService heroService;
//分页查询
@Test
public void testQueryPage(){
Page<HeroEntity> page = heroService.lambdaQuery().page(new Page<>(1,2));
System.out.println("总数:"+page.getTotal());
page.getRecords().forEach(heroEntity -> {
System.out.println(heroEntity.toString());
});
}
//根据名称查询
@Test
public void testQueryName(){
HeroEntity heroEntity = heroService.lambdaQuery().eq(HeroEntity::getHeroName,"死歌").one();
System.out.println(heroEntity.toString());
}
//插入
@Test
public void testInsert(){
HeroEntity heroEntity = new HeroEntity();
heroEntity.setHeroName("稻草人");
heroService.save(heroEntity);
}
//列表
@Test
public void testA1(){
List<HeroEntity> list = heroService.list();
list.forEach(heroEntity -> {
heroEntity.toString();
});
}
可以使用easy code自动生成相关业务代码
MybatisPlus的扩展功能
逻辑删除
逻辑删除并不是真正的将数据删除,而是给每个数据设置一个字段,用于判断是否被删除
直接在字段使用@TableLogic
或者使用全局配置
mybatis-plus:
global-config:
db-config:
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
logic-delete-field: deleted #设置全局字段名称
如果需要恢复,需自行实现相关的方法
在Mapper中自定实现更新方法
public interface TeacherDao extends BaseMapper<Teacher> {
@Update("update teacher set deleted =0 where tid = #{uid}")
public void recover(@Param("uid") Integer id);
}
在service中调用
@Service("teacherService")
public class TeacherServiceImpl extends ServiceImpl<TeacherDao, Teacher> implements TeacherService {
@Override
public void recover(Integer id){
getBaseMapper().recover(id);
}
}
枚举属性的使用
定义一个枚举
public enum GradeEnum {
//创建对象
PRIMARY(1, "小学"),
SECONDORY(2, "中学"),
HIGH(3, "高中");
//设置Enum属性后构造方法
@EnumValue
int code;
String value;
GradeEnum(int code,String value){
this.code =code;
this.value = value;
}
}
在实体类中使用一个枚举作为一个属性
@Setter@Getter
public class Student extends Model<Student> {
private Integer sid;
private String sname;
private String gender;
private Integer classId;
private GradeEnum grade; //枚举属性
}
在配置中扫描枚举类的包(指定枚举类的包名)
mybatis-plus:
typeEnumsPackage: com.java2022.mybatisplus.com