简体   繁体   中英

Composite @NaturalId in Hibernate entity

For generation id's of entities application uses trigger. So, for assigning generated values to entities we use constructions like this:

@Id
@Column(name = "INVOICE_ID")
@GeneratedValue(generator = "trigger")
@GenericGenerator(name = "trigger", strategy = "org.hibernate.id.SelectGenerator")
private Long invoiceId;

@Column(name = "INVOICE_AMOUNT")
@NaturalId(mutable = true)
private Double invoiceAmount;

SelectorGenerator requires to use @NaturalId for some field, which should has(logically) unique value. But some tables don't have anyone field which has all unique values. SelectGenerator doesn't support multiple natural id's. How can we get round this situation?

As available solution for cases like this we changed a little mechanism of getting IDs of entities. Instead of using

@GenericGenerator(name = "trigger", strategy ="org.hibernate.id.SelectGenerator")

we prefered to use database sequence generator

@Id
@Column(name = "INVOICE_ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "invoice_id_seq")
@SequenceGenerator(name = "invoice_id_seq", sequenceName = "INVOICE_ID_SEQ")
private Long invoiceId;

It doesn't requre @NaturalId and it solved our problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM