我有一个简单的测试,尝试在其中更新对象,但是合并似乎在执行插入操作而不是更新操作。
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring/app-context.xml","classpath:spring/testdb-context.xml"}) public class UserJPATest { @Test public void testUpdate() throws Exception { System.out.println("update"); User entity = ObjectManager.USER_DAO.findById(3L); entity.setUsername("harryUpdate"); ObjectManager.USER_DAO.update(entity); User selEntity = ObjectManager.USER_DAO.findById(3L); Assert.assertEquals(entity.getUsername(),selEntity.getUsername()); }
}
这是我的更新方法
@Override @Transactional(propagation= Propagation.REQUIRES_NEW) public T update(T entity) throws Exception { try { T merged = entityManager.merge(entity); return merged; } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } }
更新代码
@Override @Transactional(propagation= Propagation.REQUIRES_NEW) public T update(T entity) throws Exception { try { T merged = null; BaseEntity baseEntity = null; if(entity instanceof BaseEntity){ baseEntity = (BaseEntity)entity; merged = entityManager.find(entityClass, baseEntity.getId()); } merged = entityManager.merge(entity); entityManager.flush(); return merged; } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } }
现在,我收到以下错误无法提交JPA事务;嵌套的异常是javax.persistence.RollbackException:标记为rollbackOnly的事务
我有一个版本列,当种子数据插入数据库时未设置该列。因此,所有有关更新和删除的问题