4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

spring boot x PostgreSQL IDカラム AUTO INCREMENT

Posted at

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に指示

Thank you AI:writing_hand_tone1:

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?