使用MyBatis-Plus时居然遇到这些坑?

众所周知,MyBatis-Plus(MP)提供功能丰富的条件构造器快速进行无sql开发,但是呢?如果我们起的实体类中,出现特殊关键字的字段,MP自动生成的Sql就会无法识别哪些是自动生成的关键字!

下面举例说明上述情况:

1.首先是实体类

@Setter
@Getter
@ToString
@TableName(value = "employee")
public class Employee {
    @TableId(value="id", type=IdType.AUTO)
    private Long id;//上面注解表示主键为ID,并自增

    private String name;

    private String password;

    private String email;

    private Integer age;
    
    private Boolean admin;

    /*此注解表示映射数据库中的dept_id字段,exist默认是true,
    true表示数据库存在该字段,false的话表示不存在,一般用在非持久化字段中*/
    @TableField(value = "dept_id",exist = true)
    private Long deptId;
}

2.执行的方法

    @Test
    public void testGet(){
        //根据id来查
        Employee employee = employeeMapper.selectById(1L);
        System.out.println(employee);
    }

3.报错信息如下

### SQL: SELECT id,name,password,email,age,admin,dept_id FROM employee WHERE id=?
### Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'admin,dept_id FROM employee WHERE id=1' at line 1
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'admin,dept_id FROM employee WHERE id=1' at line 1

看到这里时我是有点懵的,当时状态一直处于在MP生成的sql怎么可能会有错,于是我复制这段sql去Navicat中测试,结果如下:

 处理了一下admin这个关键字后,又能正常执行了

 4.解决方法

在实体类中,将admin关键字端,加上@TableField("`admin`")该注解就解决了,注意是反单引号,在键盘中的esc下面那个就是反单引号,例子如下:

@Setter
@Getter
@ToString
@TableName(value = "employee")
public class Employee {
    @TableId(value="id", type=IdType.AUTO)
    private Long id;

    private String name;

    private String password;

    private String email;

    private Integer age;

    @TableField("`admin`")
    private Boolean admin;

    @TableField(value = "dept_id",exist = true)
    private Long deptId;
}

Guess you like

Origin blog.csdn.net/weixin_51263452/article/details/122467098