問題信息:
如果表名是數據庫關鍵字怎么辦?
正常來說,如果是我們自己寫sql的話,給表名加反引號即可解決問題。
但是由於我們使用MyBatisPlus,相關的sql基本上都是封裝並自動生成的。如果是這種場景,我們就需要修改對應的實體,舉例說明,如下代碼:
import com.baomidou.mybatisplus.enums.IdType; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.activerecord.Model; import java.io.Serializable; public class Group extends Model<Group> { private static final long serialVersionUID = 1L; /** * 組ID */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 組名 */ private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override protected Serializable pkVal() { return this.id; } @Override public String toString() { return "Group{" + "id=" + id + ", name=" + name + "}"; } }
用上述代碼的自動生成肯定會有問題,以單條數據查詢為例,默認是 select id,name from group where id = 1,又因為group屬於關鍵字,接下來會出現如下錯誤信息:
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'group WHERE id=1' at line 1 ; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'group WHERE id=1' at line 1] with root cause com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'group WHERE id=1' at line 1
這種錯誤信息,很容易識別,一看就是sql寫的有問題。但實際上sql並沒有問題,只不過是因為關鍵字沖突導致sql錯誤。
那么如何解決這個問題呢?
答案是只需加一個@TableName注解即可解決該問題。修改后的實體代碼如下:
import com.baomidou.mybatisplus.enums.IdType; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.activerecord.Model; import java.io.Serializable; @TableName("`group`") public class Group extends Model<Group> { private static final long serialVersionUID = 1L; /** * 組ID */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 組名 */ private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override protected Serializable pkVal() { return this.id; } @Override public String toString() { return "Group{" + "id=" + id + ", name=" + name + "}"; } }