Wednesday, June 8, 2011

Hibernate (Annotation) + PostgreSQL + Sequence Generator

Problem: The java class generated by Hibernate Code Generator does not know anything about the sequence defined on PostgreSQL.

Solution: use the combination of @javax.persistence.GeneratedValue & @org.hibernate.annotation.GenericGenerator

@Id

@Column(name = "id", unique = true, nullable = false, insertable=false)

@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "IdSeqGeneratorName")

@org.hibernate.annotations.GenericGenerator(name = "IdSeqGeneratorName", strategy = "sequence", parameters = { @Parameter(name = "sequence", value = "the_postgres_seq") })

public long getId() {

return this.id;

}



or

@Id

@Column(name = "id", unique = true, nullable = false, insertable=false)

@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "tcp_audit_seq_name")

@SequenceGenerator(name = "tcp_audit_seq_name", sequenceName = "tcp_audit_seq", allocationSize = 1)

public long getId() {

return this.id;

}

No comments:

Post a Comment