[
Date Prev][
Date Next][
Thread Prev][
Thread Next][
Date Index][
Thread Index]
[
List Home]
[eclipselink-users] JPA or EclipseLink OptimisticLockException?
|
Hi,
I need to handle the "javax.persistence.OptimisticLockException" that may happen when I try to update an entity.
When running against Oracle I saw that when I call "commit()" on the transaction it raises a RollbackException with cause of type "javax.persistence.OptimisticLockException", but some times instead of this type I get a
org.eclipse.persistence.exceptions.OptimisticLockException as cause. In the code bellow the call to persist is the only difference between the two tests.
I did the same test with H2 database and this problem did not happen.
I already have a workaround for this, so I just wanted to check if this is really a bug...
Here is my code:
@Test
public void testWithEntityManager() throws Exception {
testWithEntityManager(false);
}
@Test
public void testWithEntityManagerCreate() throws Exception {
testWithEntityManager(true);
}
private void testWithEntityManager(boolean create) throws Exception {
EntityManagerFactory emf = ctx.getBean(EntityManagerFactory.class);
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
UserEntity u = new UserEntity();
em.persist(u);
tx.commit();
changeWithJDBC(u);
u.setName("" + System.currentTimeMillis());
tx.begin();
if (create) {
UserEntity u2 = new UserEntity();
em.persist(u2);
}
em.merge(u);
try {
tx.commit();
fail("should raise RollbackException with OptimisticLockException inside");
} catch (RollbackException ex) {
ex.printStackTrace(System.out);
if (!create) {
if (!(ex.getCause() instanceof OptimisticLockException) &&
!(ex.getCause() instanceof javax.persistence.OptimisticLockException)) {
// We have to allow both because with Oracle we get an EclipseLink
// exception and with H2 we get a JPA exception.
fail("expecting an EclipseLink or a JPA exception");
}
} else {
if (!(ex.getCause() instanceof javax.persistence.OptimisticLockException)) {
fail("expecting a JPA exception");
}
}
} catch (Exception ex) {
ex.printStackTrace(System.out);
fail("unexpected exception " + ex);
} finally {
em.close();
}
}
private void changeWithJDBC(UserEntity u) throws SQLException {
Connection c = dataSource.getConnection();
Statement stm = c.createStatement();
int n = stm.executeUpdate("update lmp_user set version = version + 1 "
+ "where user_id = " + u.getPrimaryKey());
assertEquals(n, 1);
stm.close();
c.close();
}
Thanks,
Constantino.