2009-11-27 17 views
16

Qual è il modo standard per implementare un aggiornamento semplice?Come implementare il metodo update() in DAO usando EntityManager (JPA)?

Esempio: abbiamo Utente con numero di telefono NNNNNNN e ora vogliamo impostarlo su YYYYYY.

@PersistenceContext 
private EntityManager em; 

public void update (User transientUser) { 
    what should be here? 
} 

entità Utente più semplice possibile:

@Entity 
@Table (name = "USER") 
public class User { 

    @Id 
    @GeneratedValue 
    private Integer id; 

    @Column (nullable = false, unique = true) 
    private String login; 
    private String phone; 

    public User() { } 

    ... //some setters and getters 
} 
+0

em.merge (transientUser)? – marcosbeirigo

+0

forse, non sono sicuro che sia lo – Roman

+0

, questo è quello che ho adesso. Ma non l'ho ancora testato a causa del fatto che non è così facile configurare il contesto delle unit test. – Roman

risposta

33

Secondo le specifiche JPA, EntityManager#merge() sarà ritorno un riferimento a un altro oggetto rispetto a quello passato quando l'oggetto era alrea dy caricato nel contesto attuale. Quindi, preferisco tornare il risultato della merge() e scrivo il metodo update() in questo modo:

@PersistenceContext 
private EntityManager em; 

public User update (User transientUser) { 
    return em.merge(transientUser); 
} 

Quindi, usare in questo modo (saltando la parte di inizializzazione):

user.setPhone("YYYYYY"); 
user = dao.update(user); 
Problemi correlati