Mybatis-plus的简单CRUD操作
mybatis-plus之所以简洁其主要已封装好了简单单表的CRUD操作。
下面就说下mybatis-plus的简单操作:
springboot集成mybatis-plus。项目框架搭建完成pom文件导入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
.yml文件中添加配置(具体配置可查看官网)
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo?serverTimezone=GMT%2B8&characterEncoding=UTF-8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
mapper-locations: classpath*:mapper/*.xml
type-aliases-package: com.project #需要扫描的路劲
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 这里使用系统的日志实现
global-config:
# 逻辑删除配置
db-config:
# 删除前
logic-not-delete-value: 1
# 删除后
logic-delete-value: 0
mapper层继承BaseMapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
service层接口继承IService
public interface UserService extends IService<User> {
}
service实现类serviceImpl继承ServiceImpl类,ServiceImpl<Usermapper,User>是你自己的mapper层类名与实体类类名
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
以上配置完成基本就可以进行单表的CRUD操作了,下面是测试:
/*
* 普通查询
* */
@Test
public void testselect(){
User user = userMapper.selectById(3);
System.out.println(user);
}
结果:使用了mybatis-plus的日志,打印效果如下:(后面的只贴代码不在贴打印效果了)
/*
* 批量查询
* */
@Test
public void testselectBatchIds(){
List<User> userList = userMapper.selectBatchIds(Arrays.asList(3, 4, 5));
System.out.println(userList);
}
/*
* 插入数据
* */
@Test
public void testinsert(){
User user = new User();
user.setId(7);
user.setUsername("wd");
user.setPassword("1234");
int insert = userMapper.insert(user);
System.out.println(insert);
log.info("ok");
}
/*
* 修改数据
* */
@Test
public void testupdate(){
User user = new User();
user.setId(7);
user.setUsername("wh");
int update = userMapper.updateById(user);
System.out.println(update);
}
/*
* 删除数据
* */
@Test
public void testdelete(){
int deleteById = userMapper.deleteById(7);
System.out.println(deleteById);
}
分页需要配置类添加一个bean(具体查看mybatis-plus官方)
@Configuration
public class MybatisPlusConfig {
private static final Log log = LogFactory.getLog(MybatisPlusConfig.class);
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
log.info("=================初始化分页插件================");
return new PaginationInterceptor();
}
}
/*
* 分页
* */
@Test
public void testSelectPage(){
Page<User> userPage = new Page<>(1, 2);
IPage<User> userIPage = userMapper.selectPage(userPage, null);
List<User> list = userIPage.getRecords();
long total = userIPage.getTotal();
System.out.println("共有" + total+"条数据");
for (User user : list) {
System.out.println(user);
}
}
mybatis-plus中还有好多方法这边就不一一细说了,具体可查看官方