Reputation: 9766
I have two tables in my database USERS
and ADDRESSES
, each user can have many addresses.
I have build entity classes with NetBeans wizard, and it create the classes well:
@Entity
@Table(name = "USERS")
@XmlRootElement
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ID")
private Integer id;
// Some fields.......
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private Collection<Address> addressCollection;
public User() {
}
// Getters and Setters.......
}
@Entity
@Table(name = "ADDRESSES")
@XmlRootElement
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected AddressPK addressPK;
// Some fields.......
@JoinColumn(name = "USER_ID", referencedColumnName = "ID", insertable = false, updatable = false)
@ManyToOne(optional = false)
private User user;
public Address() {
}
// Getters and Setters.......
}
@Embeddable
public class AddressPK implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ID")
private int id;
@Basic(optional = false)
@NotNull
@Column(name = "USER_ID")
private int userId;
public AddressPK() {
}
}
In the session I save the User
instance of the current logged in user. But the User
's addressCollection
never updates when I change the database like:
Address newAddr = new Address();
// Sets values to newAddr......
AddressFacade addrDao = new AddressFacade();
addrDao.create(newAddr); // Succeeded
LoginManager.getCurrentUser().getAddressCollection(); // Returns the old address list.
How can I refresh the current user's instance to get the correct addressCollection
?
Upvotes: 0
Views: 2458
Reputation: 21145
First, when you have a bidirectional relationship, JPA requires that you keep both sides of the relationship in synch with each other. This allows caching entities and other performance enhancements to be enabled by many providers. In this case, when you set the USER_ID field, you should update the User's addressCollection that is affected by the change so that your object model stays in synch with what you are committing to the database.
An alternative is to force a refresh manually on the User instance. This can be done with a em.refresh(user) call, or through provider specific options and query hints. This is usually the least performant option though as it requires a database hit that isn't needed.
Upvotes: 1