MyBatis-Plus 用起来真的很舒服( 二 )


MyBatis-Plus 用起来真的很舒服

文章插图
 
该接口定义了非常多的方法,
新增接下来我们使用MyBatisPlus实现一下员工信息的增删改查,首先是新增操作:
@Autowiredprivate EmployeeMapper employeeMapper;@Testvoid contextLoads() {    Employee employee = new Employee(null,"aaa","aaa@qq.com",1,30);    employeeMapper.insert(employee);}
MyBatis-Plus 用起来真的很舒服

文章插图
 
然后执行该方法会产生一个异常:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: Could not set property 'id' of 'class com.wwj.mybatisplusdemo.bean.Employee' with value '1364829918590943234' Cause: java.lang.IllegalArgumentException: argument type mismatch
MyBatis-Plus 用起来真的很舒服

文章插图
 
这是因为我们没有为MyBatisPlus指定主键策略,MyBatisPlus共支持以下四种主键策略:

描述
AUTO
数据库ID自增
INPUT
insert前自行set主键值
ASSIGN_ID
分配ID(主键类型为Number(Long和Integer)或String)(since 3.3.0),使用接口IdentifierGenerator的方法nextId(默认实现类为
DefaultIdentifierGenerator雪花算法)
ASSIGN_UUID
分配UUID,主键类型为String(since 3.3.0),使用接口IdentifierGenerator的方法nextUUID(默认default方法)
只需在主键属性上添加@TableId注解即可设置主键策略:
@Data@NoArgsConstructor@AllArgsConstructorpublic class Employee {    @TableId(type = IdType.AUTO)    private Integer id;    private String lastName;    private String email;    private Integer gender;    private Integer age;}
MyBatis-Plus 用起来真的很舒服

文章插图
 
此时执行方法仍然出现一个异常:
### Cause: java.sql.SQLSyntaxErrorException: Table 'mybatisplus.employee' doesn't exist; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: Table 'mybatisplus.employee' doesn't exist
MyBatis-Plus 用起来真的很舒服

文章插图
 
这是因为我们的实体类名为Employee,数据表名为tbl_employee,而MyBatisPlus默认会以实体类名去数据库中寻找对应的表,导致二者无法进行映射,为此,我们还需要设置一下实体类对应的表名:
@Data@NoArgsConstructor@AllArgsConstructor@TableName("tbl_employee")public class Employee {    @TableId(type = IdType.AUTO)    private Integer id;    private String lastName;    private String email;    private Integer gender;    private Integer age;}
MyBatis-Plus 用起来真的很舒服

文章插图
 
在刚才的案例中,我们发现实体类中的属性lastName和数据表的列名last_name并不相同,但是新增数据仍然成功了,而且我们也并没有配置任何与属性名映射相关的配置,其实是因为MyBatisPlus有默认的全局策略配置,在MyBatisConfiguration配置类中有这样的一段配置:
public MybatisConfiguration() {    super();    this.mapUnderscoreToCamelCase = true;    languageRegistry.setDefaultDriverClass(MybatisXMLLanguageDriver.class);}
MyBatis-Plus 用起来真的很舒服

文章插图
 
这是配置类的无参构造方法,它将mapUnderscoreToCamelCase属性设置为true,而我们知道,该属性为true则会开启驼峰命名,所以驼峰命名映射是默认开启的,若是想关闭,则设置该属性为false即可:
mybatis-plus:  configuration:    map-underscore-to-camel-case: false
MyBatis-Plus 用起来真的很舒服

文章插图
 
我们还发现,在实体类上标注@TableId和@TableName注解让人非常不愉快,并且当实体类足够多时,这也是一个繁琐且麻烦的操作,为此,我们可以使用全局配置来解决这一问题,查看GlobalConfig类的源码,它是MyBatisPlus的全局策略配置类:


推荐阅读