当前使用版本(必填,否则不予处理)

latest 3.5.5

该问题是如何引起的?(确定最新版也有问题再提!!!)

在 postgresql 中新建 user 表,有任意字段即可。查询时(如 selectList(null)),实际执行的字段会是

SELECT id AS userId,user_name,user_nickname,user_age FROM user

那么就会返回 error - ERROR: column "id" does not exist Position: 8

这是因为 PostgreSQL 中的 user 是保留关键字,这样的 SQL 执行导致混淆,但是只要按照提示的在表名加上双引号 "user" 就可以正常执行了,对于 PostgreSQL 的查询,应该对于任意的表都包裹在 " 内,这样就可以避免这样的错误

图片

重现步骤(如果有就写完整)

  1. 新建 postgresql 表名 user
  2. 使用 mybatis-plus 做任意关于 user 的查询如:
  3. java
public List<User> selectAllUsers() {
        return userMapper.selectList(null);
    }
  • kotlin
    fun getAllUsers(): List<UserVO> {
        return userMapper.selectList(null).map { it.toUserVO() }
    }
  1. 执行,报错

报错信息

2024-01-15T05:18:15.451+08:00 ERROR 45904 --- [UserService] [io-10005-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.jdbc.BadSqlGrammarException: 
### Error querying database.  Cause: org.postgresql.util.PSQLException: ERROR: column "id" does not exist
  Position: 9
### The error may exist in org/example/userservice/mapper/UserMapper.java (best guess)
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: SELECT  id AS userId,user_name,user_nickname,user_age,user_password  FROM user
### Cause: org.postgresql.util.PSQLException: ERROR: column "id" does not exist
  Position: 9
; bad SQL grammar []] with root cause

org.postgresql.util.PSQLException: ERROR: column "id" does not exist
  Position: 9
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2713) ~[postgresql-42.6.0.jar:42.6.0]

不那么优雅的解决方案

更改表名,不要叫 user 改为 xxx_user 一切执行正常

Comment From: miemieYaho

自己在注解里加上转义符

Comment From: bling-yshs

解释一下,楼上的意思是:

@TableName("\"user\"")
public class User {
    @TableId
    String id;
    String username;
    String password;
    Integer age;
}