2

我正在尝试使用分配的 PK 将数据单次插入到表中。手动分配PK。

XML 文件

<insert id = "insertStd" parameterType = "com.org.springboot.dao.StudentEntity" useGeneratedKeys = "false" keyProperty = "insertStd.id", keyColumn = "id">
      INSERT INTO STUDENT (ID, NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) 
      VALUES (ID=#{insertStd.id}, NAME=#{insertStd.name}, BRANCH=#{insertStd.branch}, PERCENTAGE=#{insertStd.percentage}, PHONE=#{insertStd.phone}, EMAIL =#{insertStd.email});

   </insert>

服务调用方式

public boolean saveStudent(Student student){
    LOGGER.info("Student object save");
    int savedId= studentMapper.insertStd(student);
}

日志文件

org.springframework.jdbc.badsqlgrammarexception
### Error updating database Causes: cause org.postgresql.util.psqlexception error column id does not exist
HINT: There is a column named "id" in the table "student" but it can't be referenced from this part of the query. 
Position 200
### Error may exist in file [c:\.....\StudentMapper.xml]
### Error may involve in com.org.springboot.dao.StudentMapper.insertStd-InLine
### The error occurred while setting parameters
### SQL INSERT INTO STUDENT (ID, NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) 
  VALUES (ID=?, NAME=?,BRANCH=?, PERCENTAGE=?, PHONE=?, EMAIL=?);
### cause org.postgresql.util.psqlexception ERROR column "id" doesn't exist. //It did worked with JPA id assigned manually.
### There is a column named "ID" in the table "STUDENT", Bbut it cannot be referenced from the part of the query. 
4

1 回答 1

1

INSERT声明格式不正确。该VALUES子句不应包含列名。

此外,由于没有主要的自动生成,您可以删除所有其他属性。离开映射器id

注意:如果要手动分配 PK 值,则需要确保表中没有GENERATED ALWAYS列的子句。如果是这种情况,表格将忽略您提供的值,并使用自己的规则生成 PK。

采用:

<insert id="insertStd">
  INSERT INTO STUDENT (ID, NAME, BRANCH, PERCENTAGE, PHONE, EMAIL)
  VALUES (
    #{insertStd.id}, #{insertStd.name}, #{insertStd.branch},
    #{insertStd.percentage}, #{insertStd.phone}, #{insertStd.email}
  );
</insert>

您的错误很容易重现:

create table t (a int, b varchar(10));

insert into t (a, b) values (123, 'ABC'); -- succeeds
        
insert into t (a, b) values (a=123, b='ABC'); -- fails!

错误:列“a”不存在

小提琴

于 2021-03-08T12:56:50.657 回答