Roman
Roman

Reputation: 66216

How to implement update () method in DAO using EntityManager (JPA)?

What is the standard way to implement simple update?

Example: we have User with phone number NNNNNN and now we want to set it to YYYYYY.

@PersistenceContext
private EntityManager em;

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

User entity is as simple as possible:

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

Upvotes: 22

Views: 83284

Answers (2)

Pascal Thivent
Pascal Thivent

Reputation: 570595

According to the JPA specifications, EntityManager#merge() will return a reference to another object than the one passed in when the object was already loaded in the current context. So, I'd rather return the result of the merge() and write the update() method like this:

@PersistenceContext
private EntityManager em;

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

Then, use it like this (skipping the initialization part):

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

Upvotes: 56

Stefan Ernst
Stefan Ernst

Reputation: 2781

change the property and then use EntityManager merge()

http://java.sun.com/javaee/5/docs/api/javax/persistence/EntityManager.html#merge%28T%29

Upvotes: 2

Related Questions