I want the first to be generated:
@Id
@Column(name = "PRODUCT_ID", unique = true, nullable = false, precision = 12,
scale = 0)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PROD_GEN")
@BusinessKey
public Long getAId() {
return this.aId;
}
I want the bId to be initially exactly as the aId. One approach is to insert the entity, then get the aId generated by the DB (2nd query) and then update the entity, setting the bId to be equal to aId (3rd query). Is there a way to get the bId to get the same generated value as aId?
Note that afterwards, I want to be able to update bId from my gui.
If the solution is JPA, even better.
Choose your poison:
Option #1
you could annotate
bIdasorg.hibernate.annotations.Generatedand use a database trigger on insert (I’m assuming thenextvalhas already been assigned to AID so we’ll assign thecurvalto BID):I’m not a big fan of triggers and things that happen behind the scene but this seems to be the easiest option (not the best one for portability though).
Option #2
Create a new entity, persist it, flush the entity manager to get the id assigned, set the
aIdonbId, merge the entity.Ugly, but it works.
Option #3
Use callback annotations to set the
bIdin-memory (until it gets written to the database):This should work if you don’t need the id to be written on insert (but in that case, see Option #4).
Option #4
You could actually add some logic in the getter of
bIdinstead of using callbacks:Again, this will work if you don’t need the id to be persisted in the database on insert.