本章为基本使用
1.导入依赖
<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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
</dependencies>
2.编写配置文件
spring.datasource.driver-class-name=com.alibaba.druid.proxy.DruidDriver
spring.datasource.url=jdbc:mysql://localhost:3306/db_mp?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
mybatis.mapper-locations=classpath:mapper/*.xml
3.BaseMapper
public interface BaseMapper<T> extends Mapper<T> {
int insert(T entity);
int deleteById(Serializable id);
int deleteByMap(@Param("cm") Map<String, Object> columnMap);
int delete(@Param("ew") Wrapper<T> queryWrapper);
int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);
int updateById(@Param("et") T entity);
int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);
T selectById(Serializable id);
List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
T selectOne(@Param("ew") Wrapper<T> queryWrapper);
Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);
List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
}
4.IService
添加-Save
// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);
SaveOrUpdate
// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
Remove
// 根据 queryWrapper 设置的条件,删除记录
boolean remove(Wrapper<T> queryWrapper);
// 根据 ID 删除
boolean removeById(Serializable id);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map<String, Object> columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection<? extends Serializable> idList);
Update
// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根据 whereWrapper 条件,更新记录
boolean update(T updateEntity, Wrapper<T> whereWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);
Get
// 根据 ID 查询
T getById(Serializable id);
// 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
// 根据 Wrapper,查询一条记录
Map<String, Object> getMap(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
详细可以查看
CRUD 接口 | MyBatis-Plus (baomidou.com)
5.常用的注解
1@TableName
默认根据实体名称去找表
指定特定表
@TableName("t_user")
#配置数据库的统一前缀
mybatis-plus.global-config.db-config.table-prefix=t_
2@TableId
作用:显示表的实体ID
单字段id自增策略
public @interface TableId {
String value() default ""; //主键名
IdType type() default IdType.NONE; //生成的方式
}
IdType
public enum IdType {
AUTO(0),//自增
NONE(1),//未设置主键
INPUT(2),//手动输入
ASSIGN_ID(3),//默认全局唯一ID 默认雪花算法
ASSIGN_UUID(4);//全局唯一的uuid
}
设置全局的id自增策略
mybatis-plus.global-config.db-config.id-type=auto
3.@TableField
表结构中字段和实体类中的属性不一致的情况下可以设置映时关系, 如果数据库中的user_name 会自动转换成userName Mybatisplus会自动转换。
4.@TableLogic
用来进行逻辑删除的操作
单列逻辑删除
@TableLogic(value = "0",delval = "1")
配置全局逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1 mybatis-plus.global-config.db-config.logic-not-delete-value=0
6条件构造器
-
动态条件SQL
eq(boolean, column,columnValue)
替换下面的代码
if(boolean){
wrapper.eq(column,columnValue)
}
7分页查询
1.添加Page连接器配置
@Configuration
@MapperScan("com.example.mybatisplues.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return mybatisPlusInterceptor;
}
}
2.编写代码
Page<User> page = new Page<>();
page.setCurrent(2).setSize(5);
Page<User> result = userMapper.selectPage(page, null);
List<User> records = result.getRecords();
records.forEach(System.out::println);
System.out.println("result.getPages() = " + result.getPages());
System.out.println("result.getTotal() = " + result.getTotal());
System.out.println("result.hasNext() = " + result.hasNext());
System.out.println("result.hasPrevious() = " + result.hasPrevious());
代码例子:
@SpringBootTest
class MybatispluesApplicationTests {
@Autowired
private UserMapper userMapper;
@Autowired
private IUserService iUserService;
@Test
void contextLoads() {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
@Test
void add(){
User user = new User();
user.setAge(23);
user.setName("H栓");
user.setEmail("3614013@qq.com");
userMapper.insert(user);
}
@Test
void update(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.isNull("name");
User user = new User();
user.setName("wangwu");
userMapper.update(user,queryWrapper);
}
@Test
void remove(){
iUserService.removeById(1);
}
@Test
void sort(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.orderByDesc("age")
.orderByAsc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
@Test
void queryAllUser(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.and(item->{
item.like("name","a").gt("age",20);
}).or(item->{
item.isNull("email");
}).select("name");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}
@Test
void queryAllChild(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.inSql("id","select id from t_user where id < 6");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
@Test
void queryPage(){
Page<User> page = new Page<>();
page.setCurrent(2).setSize(5);
Page<User> result = userMapper.selectPage(page, null);
List<User> records = result.getRecords();
records.forEach(System.out::println);
System.out.println("result.getPages() = " + result.getPages());
System.out.println("result.getTotal() = " + result.getTotal());
System.out.println("result.hasNext() = " + result.hasNext());
System.out.println("result.hasPrevious() = " + result.hasPrevious());
}
结束MyBatis基本使用