Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
6
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

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

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;
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
6
Help us understand the problem. What are the problem?