Reputation: 3041
Building a web application using EJB & JPA in JSF I'd like to know how I can get modified fields of an entity.
Let's take an easy example :
@Entity
@Table
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "firstname", nullable = false, length = 45)
private String firstname;
// ...
}
Now in my EJB's method 'edit' :
@Singleton
public class UserService {
@PersistenceContext
protected EntityManager em;
public void edit(User user) {
this.em.merge(user);
}
}
I would like to know what has been changed, for example say "user was firstly named 'john' he is now 'johny'!".
The steps I'm doing :
1) Search User with ID 1
2) Display form (as html) helped with JSF (binding is managed by JSF)
3) firstname fields is edited
4) Form is submitted, I'm getting my User object edited
5) Before persisting it I'd like to compare with the old one
6) Problem is that I can't fetch it using this.em.find(1);
as I already got it
I tried :
@Singleton
public class UserService {
@PersistenceContext
protected EntityManager em;
public void edit(User user) {
System.out.println("USER 1 : " + user.getFirstname());
User u2 = this.em.find(User.class, 1);
System.out.println("USER 1 : " + user.getFirstname());
System.out.println("USER 2 : " + user.getFirstname());
this.em.merge(user);
System.out.println("USER 1 : " + user.getFirstname());
System.out.println("USER 2 : " + user.getFirstname());
}
}
I'm getting :
USER 1 : johny
USER 1 : johny
USER 2 : johny
USER 1 : johny
USER 2 : johny
I'm quite sure that JPA does know internally what has been modified, is there a magic way or shall I retain myself old values or query the database myself using SQL for example?
Upvotes: 1
Views: 556
Reputation: 18389
See,
But also you can just create a new EntityManager that is not in the same transaction/persistence context, so will return the data as it currently is on the database. (note this may be different than what is was to begin with, as other users may have changed the data).
Upvotes: 3