gpt4 book ai didi

hibernate - JPA Hibernate 合并执行插入而不是更新

转载 作者:行者123 更新时间:2023-12-02 19:09:17 25 4
gpt4 key购买 nike

我有一个简单的测试,我试图更新对象,但合并似乎执行插入而不是更新。

@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);
}
}


现在我收到以下错误 Could not commit JPA transaction;嵌套异常是 javax.persistence.RollbackException:事务标记为 rollbackOnly

最佳答案

我有一个版本列,当种子数据插入数据库时​​该列未设置。因此出现了更新和删除的所有问题

关于hibernate - JPA Hibernate 合并执行插入而不是更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5105043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com