Reputation: 9745
I'm new to JPA and I'm having a problem with this example code from a repository:
@Override
public boolean add(User user) {
EntityManagerFactory emf = HibernateRepositoryFactory
.getEntityManagerFactory();
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
User tempUser = null;
try {
if (user.getId() != null) {
tempUser = em.find(User.class, user.getId());
}
if (tempUser == null) {
em.persist(user);
} else {
// if so, get the differences and persist them
tempUser.setPassword(user.getPassword());
tempUser.setUserName(user.getUserName());
tempUser = em.merge(user);
}
} catch (Exception e) {
logging.error("log error+ " :" + e);
}
tx.commit();
em.close();
emf.close();
return true;
}
with entity :
@Entity
@Table(name = "USERS")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID", nullable = false, unique = true)
private Long id;
@Version
@Column(name = "OPTLOCK")
private int version;
@Column(name = "USERNAME", nullable = false)
private String userName;
@Column(name = "PASSWORD", nullable = false)
private String password;
public User() {
super();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Long getId() {
return id;
}
public int getVersion() {
return version;
}
}
I don't understand it completly.
In the line : if (user.getId() != null) user.getId will always be null because I believe the id will be generated at the moment the object will be persisted? Like this the tempUser will never be filled in from the db and the object will always be persisted and not merged .... . Or do I see this wrong?
What will be the best way to see if you need to persist or merge like this.
Edit
what if I would use a main like this :
User user1 = new User();
user1 .setPassword("password_user1");
user1 .setUserName("userName_user1");
... .add(user1);
If I run this one time the User is added. If I then run this again the User is again persisted with a id+1
Upvotes: 1
Views: 997
Reputation: 17518
You are right, if the user parameter is new (has never been persisted) then this method will persist()
it. In case it's a detached instance (has already been persisted, and has an id), it will update it by calling merge()
.
I think the method's name is misleading, it should rather be called saveOrUpdate()
.
Upvotes: 1
Reputation: 514
If the method parameter User is a persisted entity then getId() will not be null.
Upvotes: 0