Hello everbody,
Normally, inserting master-detail object to database follow these steps.
1- insert master to database cache.
When error occurred, do rollback.
2- insert detail to database cache.
When error occurred, do rollback.
3-if no error, commit transaction.
But in jpa transaction rollback is not working same, I think.
I have two objects to persist. Like these:
public class ConditionKey implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "KEY_ID")
private Integer keyId;
@OneToMany(mappedBy = "conditionKey", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<KeyOption> keyOptions;
@Entity
@Table(name = "KEY_OPTION")
public class KeyOption implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "KEY_OPTION_ID")
private Integer keyOptionId;
@Column(name = "OPTION_VALUE")
private String optionValue;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "KEY_ID")
private ConditionKey conditionKey;
KeyOption optionValue is unique in database.
When I call jpa persist I have trouble with these object. JPA insert ConditionKey to database cache. KeyOption optionValue is unique. When I insert already inserted optionValue
JPA throw en UniqunessException but ConditionKey is already changed. But database not.
How can I solve these rollback problem in JPA? (EclipseLink)
public void insertConditionKey(ConditionKey conditionKey) throws Exception {
EntityManager em = entityManagerFactory.createEntityManager();
try {
em.getTransaction().begin();
em.persist(conditionKey);
em.flush();
em.getTransaction().commit();
} catch (Exception e) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
throw e;
} finally {
em.close();
}
}
catch (Exception e) {
if (em.getTransaction().isAct
log.debug("coming to exception");
em.getTransaction().rollba
}