JPA刷新实体 [英] JPA refresh entity
问题描述
我的数据库 USERS
和 ADDRESSES
中有两个表,每个用户可以有许多地址.
I have two tables in my database USERS
and ADDRESSES
, each user can have many addresses.
我已经使用NetBeans向导构建了实体类,并且很好地创建了这些类:
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() {
}
}
在会话中,我保存当前登录用户的 User
实例.但是当我更改数据库时, User
的 addressCollection
永远不会更新:
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.
如何刷新当前用户的实例以获得正确的 addressCollection
?
How can I refresh the current user's instance to get the correct addressCollection
?
推荐答案
首先,当您具有双向关系时,JPA要求您将关系的双方保持彼此同步.这允许许多提供程序启用缓存实体和其他性能增强功能.在这种情况下,设置USER_ID字段时,应更新受更改影响的用户的addressCollection,以使对象模型与提交给数据库的对象保持同步.
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.
另一种方法是在User实例上手动强制刷新.这可以通过em.refresh(user)调用或通过提供程序特定的选项和查询提示来完成.尽管通常它不需要数据库命中,但这通常是性能最低的选项.
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.
这篇关于JPA刷新实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!