英文:
When using Spring/JPA and inserting initial data with data.sql, why is the ID column not auto-incrementing?
问题
错误:
Exception in thread "task-2" org.springframework.jdbc.datasource.init.ScriptStatementFailedException: 无法执行类路径资源[data.sql]中语句#1的SQL脚本语句:INSERT INTO kana_term(id,en_term_text,jp_term_text)VALUES(DEFAULT,'a','あ'); 嵌套异常是org.postgresql.util.PSQLException:错误:列"id"中的空值违反了非空约束
详细信息:失败的行包含(null,a,あ)。
实体:
package io.blainelafreniere.langsite.entities;
import javax.persistence.*;
@Entity
public class KanaTerm {
@Id @GeneratedValue(strategy= GenerationType.AUTO) private Long id;
@Column String jp_term_text;
@Column String en_term_text;
}
data.sql:
INSERT INTO kana_term(id,en_term_text,jp_term_text)VALUES(DEFAULT,'a','あ');
我还尝试过排除"(id)VALUES(DEFAULT)"部分:
INSERT INTO kana_term(en_term_text,jp_term_text)VALUES('a','あ');
但是我得到了相同的错误。
我以为我的实体被配置成不需要指定ID。
英文:
Error:
Exception in thread "task-2" org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of class path resource [data.sql]: INSERT INTO kana_term (id, en_term_text, jp_term_text) VALUES (DEFAULT, 'a', 'あ'); nested exception is org.postgresql.util.PSQLException: ERROR: null value in column "id" violates not-null constraint
Detail: Failing row contains (null, a, あ).
Entity:
package io.blainelafreniere.langsite.entities;
import javax.persistence.*;
@Entity
public class KanaTerm {
@Id @GeneratedValue(strategy= GenerationType.AUTO) private Long id;
@Column String jp_term_text;
@Column String en_term_text;
}
data.sql:
INSERT INTO kana_term (id, en_term_text, jp_term_text) VALUES (DEFAULT, 'a', 'あ');
I have also tried excluding the "(id) VALUES (DEFAULT)" stuff as well:
INSERT INTO kana_term (en_term_text, jp_term_text) VALUES ('a', 'あ');
And I get the same error.
I thought my entity was configured so that I didn't need to specify an ID.
答案1
得分: 3
我通过将@GeneratedValue(strategy= GenerationType.AUTO)
更改为@GeneratedValue(strategy= GenerationType.IDENTITY)
来解决了我的问题。
英文:
I fixed my issue by changing @GeneratedValue(strategy= GenerationType.AUTO)
to @GeneratedValue(strategy= GenerationType.IDENTITY)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论