Tôi có một thử nghiệm đơn giản, nơi tôi đang cố gắng cập nhật đối tượng, nhưng hợp nhất dường như đang thực hiện chèn thay vì cập nhật.JPA Hibernate merge thực hiện chèn thay vì cập nhật
@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());
}
}
Đây là phương pháp cập nhật của tôi
@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);
}
}
Cập nhật mã
@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);
}
}
Bây giờ tôi nhận được lỗi sau đây không thể cam kết giao dịch JPA; ngoại lệ lồng nhau là javax.persistence.RollbackException: Giao dịch được đánh dấu là rollbackOnly
Làm thế nào để bạn xác định rằng nó thực hiện chèn? – axtavt
Tôi không ** thực sự ** như tuyên truyền ** REQUIRES_NEW **, bạn có thể đang tạo đối tượng trong một TX và sau đó thực hiện "hợp nhất hoặc cập nhật" trong một TX khác, không biết về bản gốc thực thể. – Augusto
Tôi đã kiểm tra các bản ghi và nó cố gắng để làm một chèn – user373201