javadatabasehibernatetriggersnaturalid

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?


Solution

  • 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.