使用MyBatis的时候,经常需要书写类似
SELECT id,name,age,email FROM user WHERE id=#{id}
这样的语句,而且当增加字段后,还需要逐条语句都检查。 使用MyBatis-Plus后可以摆脱大部分此类简单的CRUD操作(通用Mapper也可以)。
效果对比
- 使用前
public interface UserMapper {
@Select("SELECT id,name,age,email FROM user WHERE id=#{id}")
User selectOne(@Param("id") int id);
}
- 使用后
public interface UserMapper extends BaseMapper<User> {
}
没有xml,没有sql
- 调用方
User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getAge, 1));
User userOne = userMapper.selectById(1);
Integer count = userMapper.selectCount(null);
List<User> users = userMapper.selectBatchIds(Lists.newArrayList(1, 2, 3));
List<User> users = userMapper.selectList(Wrappers.<User>lambdaQuery().eq(User::getAge, 18));
快速接入(Spring boot)
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.1-jre</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/tenmao?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8
spring.datasource.username=tenmao
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- 实体类
@Data
public class User {
private Integer id;
private String name;
private Integer age;
private String email;
}
- Mapper
public interface UserMapper extends BaseMapper<User> {
}
- 使用方
@Slf4j
@MapperScan("com.tenmao.plus.mapper")
@SpringBootApplication
public class PlusApplication {
@Resource
private UserMapper userMapper;
public static void main(String[] args) {
SpringApplication.run(PlusApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
log.info("start to select user");
System.out.println(userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getAge, 28)));
System.out.println(userMapper.selectById(1));
System.out.println(userMapper.selectCount(null));
};
}
}
优点
MyBatis-Plus与通用Mapper的优点类似。参考MyBatis & 通用Mapper
-
为最常见的语句提供内置接口,不需要写任何SQL。比如:
- selectOne
- selectById
- selectCount
- 方法太多,省略其他...
针对高级一点的查询,可以使用
Wrappers
机制
userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getAge, 28))
- 也支持标准的MyBatis的接口使用方式
注解方式
public interface UserMapper extends BaseMapper<User> {
@Select("SELECT * FROM user WHERE age=#{age}")
List<User> selectByAge(@Param("age") int age);
}
xml文件方式
application.properties
mybatis-plus.mapper-locations=classpath:mapper/*_mapper.xml
mapper/user_mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tenmao.plus.mapper.UserMapper">
<select id="selectByEmail" resultType="com.tenmao.plus.domain.User">
SELECT * FROM `user` WHERE email = #{email}
</select>
</mapper>
其他配置
-
mybatis-config.xml
位置配置
mybatis-plus.config-location=classpath:mybatis-config.xml
主键配置:
@TableId
与数据库没有对应关系的字段:
@TableField(exist = false)
typeHandler
全局配置
mybatis-plus.type-handlers-package=com.tenmao.utils.mybatis.handler
单独配置
比通用mapper麻烦很多,读取与插入还需要分开配置,而且还要用到xml配置
<resultMap id="baseResult" type="com.tenmao.plus.domain.User">
<result property="hobbies" column="hobbies" typeHandler="com.tenmao.plus.handler.ListTypeHandler" />
</resultMap>
@Data
//读取数据库时使用resultMap
@TableName(resultMap = "baseResult")
public class User {
private Long id;
private String name;
private Integer age;
private String email;
//插入数据库时,使用下面的注解
@TableField(el="hobbies, typeHandler=com.tenmao.plus.handler.ListTypeHandler")
private List<String> hobbies;
}
常见错误
org.apache.ibatis.reflection.ReflectionException: Could not set property 'id' of 'class com.tenmao.plus.domain.User'
插入记录的时候如果没有指定ID,则会使用默认策略
IdType.ID_WORKER
(生成一个全局唯一ID)。这个ID是long类型,如果实体类的id
是int
,就会报错。 解决办法是在id上添加注解:@TableId(type = IdType.AUTO)
,或者全局配置mybatis-plus.global-config.db-config.id-type=auto