Java協程
阿新 • • 發佈:2021-02-06
技術標籤:mybatis-plusjavamybatisspring boot
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中還有好多方法這邊就不一一細說了,具體可檢視官方