I have set FlushModeType to COMMIT, but right after em.persist() call, the INSERT is made to database. I expect Hibernate to write changes to database only at the end of transaction, but it seems to work differently.
Little code to illustrate the problem:
@Entity
@Table(name="tbl1")
@Inheritance(strategy=InheritanceType.JOINED)
public class TopLevelEntity {}
@Entity
@Table(name="tbl2")
public class MyEntity extends TopLevelEntity {
AnotherEntity anotherEntity;
//getters and setters
}
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class AnotherEntity { }
public void someTransaction() {
em.setFlushMode(FlushModeType.COMMIT);
MyEntity e = new MyEntity();
em.persist(e);
e.setProp1(someVal1);
e.setProp2(someVal2);
}
Here I expect, that the actual INSERT will be made at the end of method, right after setProp2() call.
But Hibernate does the insert right after calling em.persist()
.
Can somebody explain me this behaviour?
Edit:
I even tried using FlushMode.MANUAL for Hibernate Session, but it performs INSERT after em.persist
anyway. So, is there no way to manually control when flush is done?
Edit2:
Here is the issue, which I'm facing. I have an entity A
which has-a entity B
. Entity B
doesn't exist yet during the call to em.persist(a)
, and I have a 'CONSTRAINT CHECK (B IS NOT NULL) in the database`. The only workaround which I found is to use deferred constraint in Oracle. However, this solution is vendor-specific and doesn't really satisfy me.
Edit3:
Cascade seems like a good solution, but in our project we're not allowed to use it. We're encouraged to manually control all the inserts and updates.
FlushMode Commit does not guarantee that the commit will happen at transaction commit. It is more of a hint for the provider (implementator of specs, like Hibernate here), but he can do it whenever he chooses. If you want to persists/update a bean which has a new dependency that doesn't exist yet in the database. use Cascade on persists/merge operations to persist it as well. IF you declared a field/dependency as not-nullable than it's normal for JPA not to let you save an entity with that field/dependecy null, as it enforces the constrains you put on it. What you want to do there is pretty much a hack/workaround around the JPA specs. you either make that field/dependency nullable if in fact it can sometimes be null, or you make sure that it's never null (and cascaded if it's new value) when you persist the parent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With