Ho un semplice test, in cui sto cercando di aggiornare l'oggetto, ma l'unione sembra eseguire un inserto invece di un aggiornamento.JPA Hibernate merge esegue l'inserimento invece dell'aggiornamento
@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());
}
}
Questo è il mio metodo di aggiornamento
@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);
}
}
Update per codice
@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);
}
}
Ora ottengo il seguente errore non poteva commettere transazioni JPA; l'eccezione nidificata è javax.persistence.RollbackException: Transazione contrassegnata come rollbackOnly
Come si determina che esegue l'inserimento? – axtavt
Non mi piace molto ** ** la propagazione ** REQUIRES_NEW **, potresti creare l'entità in un TX e quindi fare un "unione o aggiornamento" in un TX diverso, che non conosce l'originale entità. – Augusto
Ho controllato i registri e tenta di fare un inserto – user373201