Hibernate: same generated value in two properties
I want the first one 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 bId to be exactly like aId initially. One approach is to insert an object, then get the aId generated by the DB (second query), and then update the object by setting bId equal to aId (third query). Is there a way to get bId to get the same generated value as aId?
Please note that I want to update the bId from my gui afterwards.
If the solution is JPA, even better.
a source to share
Select poison:
Option number 1
you could annotate bId
like org.hibernate.annotations.Generated
and use the database trigger for insert (I assume the nextval
AID is already assigned, so we'll assign the curval
BID):
CREATE OR REPLACE TRIGGER "MY_TRIGGER"
before insert on "MYENTITY"
for each row
begin
select "MYENTITY_SEQ".curval into :NEW.BID from dual;
end;
I'm not a big fan of triggers and things that happen behind the scenes, but this is probably the easiest option (not the best for portability).
Option number 2
Create a new object, save it, clear the object manager to get the assigned id, set aId
on bId
, merge the object.
em.getTransaction().begin();
MyEntity e = new MyEntity();
...
em.persist(e);
em.flush();
e.setBId(e.getAId());
em.merge(e);
...
em.getTransaction().commit();
Ugly, but it works.
Option number 3
Use callback annotations to set bId
in memory (until it is written to the database):
@PostPersist
@PostLoad
public void initialiazeBId() {
if (this.bId == null) {
this.bId = aId;
}
}
This should work if you don't need the ID to be written on the insert (but in this case, see Option # 4).
Option number 4
You can actually add some logic to the getter bId
instead of using callbacks:
public Long getBId() {
if (this.bId == null) {
return this.aId;
}
return this.bId;
}
Again, this will work if you don't want the ID to be stored in the database on insert.
a source to share