在项目中如果我们实体对应的表中包含数据库的关键字,就会出现如下异常信息:

### Error querying database.  Cause: java.sql.SQLSyntaxErrorException: (conn=684898) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'order,parent  FROM typecho_metas 
### The error may exist in com/youth/mapper/TypechoMetasMapper.java (best guess)
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: SELECT  mid,name,slug,type,description,count,order,parent  FROM typecho_metas     WHERE mid = ?
### Cause: java.sql.SQLSyntaxErrorException: (conn=684898) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'order,parent  FROM typecho_metas 
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: (conn=684898) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'order,parent  FROM typecho_metas ] with root cause

java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'order,parent  FROM typecho_metas 
 
 WHERE mid = '1'' at line 1
    at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.readErrorPacket(AbstractQueryProtocol.ja

    ......

出现这种情况,我们就需要重新甚是一下数据库表字段名称设计是否不合理。
由于数据表字段名称与MySQL数据库关键字或者预留关键字一致,在这种情况下,就会导致SQL执行不成功。

解决办法:
一、Mybatis中解决方案
1、针对XML文件,可以在冲突的字段名添加 ( 反单引号在 键盘Esc键下面的那个,注意切换英文输入法 ) 引起来

insert into my_blog.typecho_metas
(
    name,
    slug,
    `type`,
    description,
    count,
    `order`,
    parent
)
values
(
    #{d.name},
    #{d.slug},
    #{d.type},
    #{d.description},
    #{d.count},
    #{d.order},
    #{d.parent}
);

2、如果不想修改xml文件,也可针对实体类进行修改,可以通过添加@Column注解,如下所示:

@Column(name = "`type `")
private String type;

@Column(name = "`order`")
private String order;

二、MybatisPlus解决方案

直接在实体类上添加 @TableField 注解,给上别名加上反单引号即可

@TableFiled(value = "`type `")
private String type;

@TableFiled(value = "`order `")
private String order;

标签: Java, 解决实体对应字段与数据库关键字冲突, 字段与数据库关键字

添加新评论