MyBatis-Plus对MyBatis只做增强不做改变,简化开发,我们用MyBatis-Plus可以非常轻松的实现单表的增删改查,在也不用写大量的sql了。
用MyBatis-Plus的开发步骤:
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
dependency>
<dependency>
<goupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
spring:
application:
name: backend-service
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
username: root
password: 123456
mybatis-plus:
configuration:
# 在控制台打印sql
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
global-config:
# 全局的id生成策略
db-config:
id-type: assign_id # 全局的id生成策略
# 扫描xml配置文件,一般自定义的sql时使用
mapper-locations: classpath*:mapper/*.xml
这里的实体类用User作为示例
@Data
@TableName("sd_user") // 指定表名和实体类之间的关系,如果不指定的,则默认跟类名一致
public class User {
@TableId(type = IdType.ASSIGN_ID) // 主键生成策略,也可以在yml文件中配置全局的uuid生成策略,局部uuid生成策略高于全局的
private Long id;
@TableField("name") // 指定数据库字段跟属性的关系
private String name;
private Integer age;
/**
* 备注
*/
@TableField(exist = false) // 数据库字段没有remark,用这个属性来排除
private String remark;
}
需要了解详细注解及属性值可以参考官网https://baomidou.com/reference/annotation/
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
编写到了这一步,就可以使用UserMapper类对数据表进行增删改查的操作了。
userMapper.selectById(id);
userMapper.selectBatchIds(ids);
Map<String, Object> columnMap = new HashMap<String, Object>();
columnMap.put("name", "张三"); // name是数据库表的列名
columnMap.put("age", 20);
userMapper.selectByMap(columnMap);
查询构造器中使用的方法,一般就和sql的查询方法类似,在sql中怎么用,在查询构造器里就怎么拼,一般就可以实现。
由于上边配置了sql打印,就可以在执行的过程中看到编写的代码执行后到底符不符合预期。
在查询的时候如果没有指定列的话,查询的是实体类里边有的列。想要查个别字段的话用select
方法来指定。
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
// like有三个参数,参数1:判空,参数2:列名,参数3:参数值
// 参数如果为空,则不会被拼接到where条件后
queryWrapper.select("id").like(StringUtils.isNotEmpty(name), "name", name);
User whereUser = new User();
whereUser.setId(1l);
// whereUser作为参数传递时,也会作为条件加入到where条件中
QueryWrapper<User> queryWrapper = new QueryWrapper<>(whereUser);
// like模糊查询 lt 小于
queryWrapper.like("name","张").lt("age", 30);
LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
LambdaQueryWrapper<User> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
objectLambdaQueryWrapper.like(User::getName,"张")
.and(u -> u.lt(User::getId,1).or().isNotNull(User::getName));
// 直接调用list方法返回结果
List<User> userList = new LambdaQueryChainWrapper<User>(userMapper)
.like(User::getName,"张").ge(User::getId,20).list();
userList
方式1
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id",1);
User user = new User();
user.setName("lisi"); // set的值
// 参数1需要更新的列及值,参数2:更新所需要的where条件
userMapper.update(user,updateWrapper);
方式2
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id",1).set("name","ww"); // set的列为name
userMapper.update(null,updateWrapper);
userMapper.insert(user);
在使用分页的时候,需要MyBatis-Plus提供的插件
@Configuration
public class MyBatisPlusPageConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加
// 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
return interceptor;
}
}
使用分页
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.ge(User::getAge, 20);
// false的意思是,不执行count(*)计算数据条数的sql
Page<User> page = new Page<>(1,2,false);
Page<User> userPage = userMapper.selectPage(page, queryWrapper);
System.out.println(Arrays.asList(userPage));
MyBatis-Plus还提供了通用的Service层接口,用它可以实现基本的增删改查、分页等操作。
使用方法如下
public interface MyUserService extends IService<User> {
}
@Service
public class MyUserServiceImpl extends ServiceImpl<UserMapper,User> implements MyUserService {
}
我们就可以通过MyUserService来实现基本的对数据库的操作了。
官方文档https://baomidou.com/guides/data-interface/
不管是使用常规的Mapper接口,还是用通用的Service接口,其目的一般都是简化对数据库的操作。