LoginSignup
7
6

More than 5 years have passed since last update.

PostgreSQL+JPAのIDカラムで「relation "hibernate_sequence" does not exist」となったときの対処

Posted at

PostgreSQL+JPAのIDカラムでシーケンス利用時にエラーになった際の対処メモ。

現象

PostgreSQL(10.0)で

create table employee (
  employee_id serial not null,
  employee_name text,
  constraint employee_PKC primary key (employee_id)
);

のようなテーブルがあったときに、JPAで

@Entity
public class Employee {
    @Id
    @SequenceGenerator(name = "employee_employee_id_seq")
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Integer employeeId;

    private String employeeName;

    // Getter/Setter
}

とアノテーションを付与しておくと、レコードのsave時に

org.postgresql.util.PSQLException: ERROR: relation "hibernate_sequence" does not exist

というエラーが出た。
どうやら、デフォルトのシーケンス名が参照されてしまう模様。

対処

2通りある。

シーケンス名を明示的に指定する方法

何回もシーケンス名を書かないといけないのが難点。

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "employee_employee_id_seq")
@SequenceGenerator(name = "employee_employee_id_seq", sequenceName = "employee_employee_id_seq")
private Integer employeeId

GenerationType.IDENTITYを使用する方法

こちらの方がシンプル。

@Id
@SequenceGenerator(name = "employee_employee_id_seq")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer employeeId;
7
6
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
7
6