开发者

JPA Hibernate merge performs insert instead of update

开发者 https://www.devze.com 2023-02-12 23:30 出处:网络
I have a simple test, where I am trying to update the object, but merge seems to be performing an insert instead of update.

I have a simple test, where I am trying to update the object, but merge seems to be performing an insert instead of update.

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

}

This is my update method

@Override
@Transactional(propagation= Propagation.REQUIRES_NEW)
public T update(T entity) throws Exception {
    try {
        T merged = entityManage开发者_JAVA百科r.merge(entity);
        return merged;
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception(e);
    }
}

Update to code

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

Now I get the following error Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly


I had a version column which was not set when seed data was inserted into database. Hence all the problems with update and delete


Merge will update the row ONLY IF it founds the id in the database, so if you create a new object and forgot to set its ID to the same ID of the desired row, it will try to insert a new one. In case your database table doesn't have any unique field, probably this insert will be successful as there will be no sql error.

I was able to update the desired row once I set the new object with the ID of that row.

0

精彩评论

暂无评论...
验证码 换一张
取 消