Mybatis Plus官网:https://mp.baomidou.com/
优点:对于单数据库表操作便利,且不影响原有Mybatis功能,只做增强
1.添加Mybatis Plus依赖
pom.xml
<!--Mybatis Plus-->
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
2.数据库
t_user表
CREATE TABLE `NewTable` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
`role_id` int(11) NULL DEFAULT NULL ,
`createtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
AUTO_INCREMENT=13
ROW_FORMAT=DYNAMIC
3.对Bean基础类添加注解
User
@TableName("t_user") // 数据库表格名称
public class User {
/**
* value 对应数据库表格中主键的字段名称
* type IdType.AUTO枚举类,意味对应数据库中的主键自动增长
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String username;
private String password;
private Integer roleId;
private Date createtime;
// set/get,构造函数及toString省略...
}
4.MP配置类
MybatisPlusConfig配置类
@Configuration
@MapperScan("com.cx.mybatis.mapper")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
}
5.在已有的Spring Boot Mybatis工程基础上继承BaseMapper
UserMapper
public interface UserMapper extends BaseMapper<User> {
}
6.测试功能
UserTest测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTest {
@Autowired
UserMapper userMapper;
@Test
public void test01() {
// 运用自带CRUD接口方法
User user = userMapper.selectById(2);
System.out.println(user);
}
@Test
public void test02() {
// 运用条件构造器方式查询
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("password", "123");
List<User> userList = userMapper.selectList(queryWrapper);
for (User user : userList) {
System.out.println(user);
}
}
}
运行结果
test01
test02