My Quotes

When U were born , you cried and the world rejoiced
Live U'r life in such a way that when you go

Thursday, April 18, 2013

Manage a composite primary key with an incremental id using JPA and Oracle

The regular way of doing this is to  have a Composite Key Class and mapping the field to use oracle sequence. In most of the scenarios this will fail.
The alternative is to 
1. Create the Composite Primary key as a regular java POJO with no @Column mappings.
2.Create/Override the equals() and hashCode() methods in this class.
3. Now go to the main POJO and instead of defining this composite key as @EmbeddedId, declare the composite primary key attributes your entity, associate the ID class with the entity and define the ID generation strategy,
o   @Id
o   @Column mappings
o   and for the sequence number field alone add like the following
  @Column(name="<>")   @GeneratedValue(strategy=GenerationType.AUTO, generator="<>")   @SequenceGenerator(name="<>", sequenceName="<>") 4.When you create the records, you don’t need to set this field at all. 5. DB will generate the sequence for you. 6.It’s a known defect from JPA that composite keys cannot accept sequence numbers  

No comments :