mybatis plus是mybatis的一个增强框架,可以更加方便的进行数据持久化
一.引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
二.配置别名
mybatis-plus:
type-aliases-package: com.tledu.springbootmybatis.domain
三.编写代码
1.实体类
package com.tledu.springboot04.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
import java.util.List;
@Data
@TableName("role")
public class Role {
@TableId(type = IdType.AUTO)
private Integer id;
private String roleName;
private Integer roleType;
private Integer status;
private Integer delState;
private Date createTime;
private Date updateTime;
//关联表字段
//忽略该字段(单表查询不需要)
@TableField(exist = false)
private List<Resources> resList;//资源list
}
2.mapper
package com.tledu.springboot04.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tledu.springboot04.domain.Role;
/**
* @author Antg
* @date 2021/8/27 14:45
*/
public interface RoleMapper extends BaseMapper<Role> {
//什么都不用写,都已经封装好了
}
3.测试CRUD
package com.tledu.springboot04;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tledu.springboot04.domain.Role;
import com.tledu.springboot04.mapper.RoleMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
/**
* @author Antg
* @date 2021/8/27 14:49
*/
@SpringBootTest
public class RoleMapperTest {
@Autowired
RoleMapper roleMapper;
//添加
@Test
public void add() {
Role role = new Role();
role.setRoleName("超级管理员");
role.setRoleType(0);
roleMapper.insert(role);
}
//删除
@Test
public void del() {
roleMapper.deleteById(1);
}
//编辑
@Test
public void update() {
Role role = new Role();
role.setId(2);
role.setRoleName("超级管理员123");
roleMapper.updateById(role);
}
//查询
@Test
public void select() {
QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
List<Role> roles = roleMapper.selectList(queryWrapper);
System.out.println(roles);
}
@Test
//带条件查询
public void selectWithRequirement() {
QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("role_name", "超级管理员1");
List<Role> roles = roleMapper.selectList(queryWrapper);
System.out.println(roles);
}
}