【发布时间】:2011-07-03 13:35:27
【问题描述】:
我有一个简单的测试,我试图更新对象,但合并似乎是在执行插入而不是更新。
@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
【问题讨论】:
-
如何确定它执行插入?
-
我真的不喜欢 REQUIRES_NEW 传播,您可能正在 TX 中创建实体,然后执行“合并或更新”在不同的 TX 中,它不知道原始实体。
-
我检查了日志并尝试插入
-
致奥古斯托....这是有道理的。我更改了代码,但现在我将事务标记为仅回滚。我已经更新了上面的代码