使用Spring/JPA并通过data.sql插入初始数据时,为什么ID列没有自动递增?

huangapple go评论78阅读模式
英文:

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_termiden_term_textjp_term_textVALUESDEFAULT'a''あ';

我还尝试过排除"(id)VALUES(DEFAULT)"部分:

INSERT INTO kana_termen_term_textjp_term_textVALUES'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)

huangapple
  • 本文由 发表于 2020年8月27日 12:54:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63609421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定