springboot2.5.5集成mybatis-plus 3.4.3.4

最新版本的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

后续会持续更新。


原文地址:https://www.cnblogs.com/baoyi/p/springboot_mybatis-plus.html