I've recently added JTA (Atomikos, but had same problem with Bitronix) to my spring+Hibernate JPA application in order to have XA support, and I've run into a very odd problem which after MANY hours of debugging I've managed to track down the source.
Basically everything works fine until I try to persist an object with a foreign key relationship (with or without cascade, makes no differenc). For example:
Code:
@Entity
public class TestObj {
@Id
private int id;
@OneToOne
private TestObj2 testObj2;
public TestObj() {
}
public TestObj(int id) {
this.id = id;
}
public TestObj(int id, TestObj2 testObj2) {
this.id = id;
this.testObj2 = testObj2;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
@Entity
public class TestObj2 {
@Id
private int id;
public TestObj2() {
}
public TestObj2(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public void testDb() {
tx.execute(status -> {
entityManager.persist(new TestObj3(0));
TestObj2 o2 = new TestObj2(0);
entityManager.persist(o2);
TestObj o1 = new TestObj(0, o2);
entityManager.persist(o1);
// If i flush the problem disapears
// entityManager.flush();
return null;
});
}
When i try to do so, it gives me an error:
ERROR: HHH000346: Error during managed flush [Session/EntityManager is closed]
No other logs or indication of what the cause of the entity manager being closed before the end of the transaction.
After trying many things, I found out that if i flush the entity manager, that fixes the problem, although i did specifically persist both objects. This differs from when i just use normal JPA transactions (flush not required)
Anyone knows why this is happening, and is this really the only way around the problem when using JTA ? Also does anyone knows if doing the entityManager.flush impact performance (I would have thought it doesn't?)
I've got a project with unit tests that replicate the problem:
https://github.com/Kloudtek/ktspring (the unit tests are those for standalone/atomikos-artemis-hibernate
UPDATE:
To make matters worse, i've got once case where flushing isn't help... trying to persist the object with foreign key just causes the entity manager to get closed no matter how many flushes are before/after