最新版本的springboot集成mybatis plus(3.4.3.4)
1. 引入pom
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.4</version>
</dependency>
<!-- Mysql驅動包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 增加jdbc的支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
2. 新增實體
@Data
@TableName("sys_user")
public class User implements Serializable {
private String userName;
private String password;
@TableId(value = "user_id", type = IdType.AUTO)
private String userId;
}
3. 新增mapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
User getUserById(Long id);
}
注意:掃描mapper包既可以在啟動類中增加
@MapperScan("com.tcrj.mybatistest.mapper")
也可以在類上直接增加@Mapper 注解,兩種方式都可以。
4. 新增service
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Long id) {
return userMapper.getUserById(1L);
}
public User selectById(Long id) {
return userMapper.selectById(1L);
}
public IPage<User> getAll() {
Page<User> userPage = new Page<>(0, 10);
return userMapper.selectPage(userPage, null);
}
}
5. 新增controller
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/getUserById")
private User getUserById() {
return userService.getUserById(1L);
}
@GetMapping("/getAll")
private IPage<User> getAll() {
return userService.getAll();
}
}
6. 新增分頁
// 最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
7. 遇到的問題
1. org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.tcrj.mybatistest.mapper.UserMapper.selectById
當在實體對象中沒有增加主鍵屬性,在調用 selectById的時候就報這個錯誤,
2. 分頁不起作用
需要注入mybatis plus 的配置
// 最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
之前的版本是這樣的:
@Bean
public PaginationInnerInterceptor paginationInnerInterceptor() {
return new PaginationInnerInterceptor();
}
是不起作用的。
8. demo git地址:
https://github.com/jamesbaoyi/mybatisplus-test.git
后續會持續更新。