我的数据库USERS
和ADDRESSES
中有两个表,每个用户可以有多个地址。
我使用NetBeans向导构建实体类,并且它可以很好地创建类:
@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() {
}
}
在会话中,我保存当前登录用户的User
实例。但是当我更改数据库时,User
&#39; addressCollection
永远不会更新:
Address newAddr = new Address();
// Sets values to newAddr......
AddressFacade addrDao = new AddressFacade();
addrDao.create(newAddr); // Succeeded
LoginManager.getCurrentUser().getAddressCollection(); // Returns the old address list.
如何刷新当前用户的实例以获取正确的addressCollection
?
答案 0 :(得分:1)
首先,当您有双向关系时,JPA要求您保持关系的两边彼此同步。这允许许多提供程序启用缓存实体和其他性能增强。在这种情况下,当您设置USER_ID字段时,您应该更新受更改影响的用户的addressCollection,以便您的对象模型与您提交给数据库的内容保持同步。
另一种方法是在User实例上手动强制刷新。这可以通过em.refresh(用户)调用,或通过提供程序特定的选项和查询提示来完成。这通常是效率最低的选项,因为它需要不需要的数据库命中。