当从 JPA 会话外部更改数据库中的值时,我遇到了实体未刷新的问题。例如,我有一个用户实体:
@Entity
@Cacheable(false)
public class UserBean implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToMany(mappedBy = "receiver")
@JoinTable(name = "NOTIFICATIONS_RECEIVED")
private List<NotificationBean> notificationsReceived;
...
}
和通知实体:
@Entity
@Cacheable(false)
public class NotificationBean implements Serializable{
@Id
@GeneratedValue
private Long id;
@ManyToOne
private UserBean receiver;
...
}
我在 JSF 应用程序中使用它并有一个 SessionScoped bean,它在登录后加载用户并存储它:
@Named("sessionManager")
@SessionScoped
public class SessionManagerBean implements Serializable {
@PersistenceUnit(unitName = "PU")
private EntityManagerFactory emf;
private UserBean user;
public UserBean getUser() throws Exception {
if (user == null) {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
String username = request.getRemoteUser();
if (username != null) {
EntityManager em = null;
try {
utx.begin();
em = emf.createEntityManager();
Query query = em.createQuery("SELECT u from UserBean u WHERE u.username = ?1");
query.setParameter(1, username);
user = (UserBean) query.getSingleResult();
}
catch (Exception e) {
try {
utx.rollback();
} catch (Exception e) {
} finally {
utx.commit();
em.close();
}
}
return user;
}
}
}
public void refreshUser() {
EnitytManager em = emf.createEntityManager();
// similar code as above to retrieve the user from the database
em.refresh(user);
}
}
加载时显示通知调用的页面refreshUser()
:
<f:metadata>
<f:event type="preRenderView" listener="#{sessionManager.refreshUser()}" />
</f:metadata>
但是,当我刷新页面时,不会刷新用户数据,并且不会更新页面上显示的通知。
但是,如果我更改refreshUser()
为:
public void refreshUser() {
EntityManager em = emf.createEntityManager();
List<NotificationBean> notifications = em.createNativeQuery("SELECT * FROM NOTIFICATIONBEAN WHERE RECEIVER_ID = " +
user.getId() + ";").getResultList();
user.setMatchChallengesReceived(notifications);
}
通知已更新。
我有比需要从数据库刷新的通知更多的变量,并且要为每个通知执行相同的操作需要很多代码。我认为em.refresh(user)
应该为我重新加载从数据库中更改的所有变量。我认为这是一个缓存问题,所以我添加@Cacheable(false)
了UserBean
and NotificationBean
,但它没有效果。
我究竟做错了什么?