2011-02-24 17 views
15

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

+0

Come si determina che esegue l'inserimento? – axtavt

+0

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

+0

Ho controllato i registri e tenta di fare un inserto – user373201

risposta

22

Avevo una colonna versione che non era impostata quando i dati seme sono stati inseriti nel database. Quindi tutti i problemi con l'aggiornamento e l'eliminazione

+0

ben fatto, mi sono imbattuto nello stesso problema .. :) –

+0

Grazie a user373201, avevo faticato con questo e ho trovato il tuo suggerimento, non appena ho cambiato la versione, ha iniziato a funzionare come era supposto di Grazie. Colonna di versione – Richipal

+0

, quale, avendo anch'essa lo stesso problema, ho impostato tutte le colonne del database, ma continua ad inserire record invece di update.help – Mufrah

Problemi correlati