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;