我有一个简单的测试,我试图更新对象,但合并似乎是执行插入而不是更新。JPA休眠合并执行插入而不是更新
@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的事务
你如何确定它执行插入? – axtavt 2011-02-24 13:07:35
我不**真的**喜欢** REQUIRES_NEW **传播,您可能会在TX中创建实体,然后在不同的TX中进行“合并或更新”,而不知道原始的实体。 – Augusto 2011-02-24 13:48:17
我检查了日志,它试图做一个插入 – user373201 2011-02-24 15:21:09