IdカラムのAUTO INCREMENTが働かない
@GeneratedValue(strategy = GenerationType.IDENTITY)
追記してるのになぜ?
@Entity
@Table(name="todos")
public class Todo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "content", nullable = false)
private String content;
@Column(name = "done")
private Boolean done = false;
}
Not Null指定してるのに新しいTodoを追加する時、
自動でIdカラムにIdが追加されず、Nullなんやがと言われる...
Error updating database. Cause: org.postgresql.util.PSQLException: ERROR: null value in column "id" of relation "todos" violates not-null constraint Detail: Failing row contains (null, shopping, 2025-03-20 02:04:51.057386, null, null).
カラムのデータ型が原因
Idカラムのデータ型が bigint
Column | Type | Collation | Nullable | Default
------------+--------------------------------+-----------+----------+---------
id | bigint | | not null |
content | character varying(255) | | not null |
created_at | timestamp(6) without time zone | | |
delete | timestamp(6) without time zone | | |
done | boolean | | |
データ型をSERIALに変更
# 既存の主キー制約の削除
ALTER TABLE todos DROP CONSTRAINT todos_pkey;
# SERIALと主キーを持つ新しいidカラムを追加
ALTER TABLE todos ADD COLUMN id SERIAL PRIMARY KEY;
Column | Type | Collation | Nullable | Default
------------+--------------------------------+-----------+----------+-----------------------------------
content | character varying(255) | | not null |
created_at | timestamp(6) without time zone | | |
delete | timestamp(6) without time zone | | |
done | boolean | | |
id | integer | | not null | nextval('todos_id_seq'::regclass)
nextval('todos_id_seq'::regclass) とは??
PostgreSQLでは、nextval('sequence_name')はシーケンスから次の値を取得するため
nextval('todos_id_seq')
: todos_id_seqシーケンスから次の数値を取得
'todos_id_seq'::regclass
: todos_id_seqをシーケンスオブジェクトとして扱うようPostgreSQLに指示