1

当从 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)UserBeanand NotificationBean,但它没有效果。

我究竟做错了什么?

4

1 回答 1

3

如果问题出在通知上,那么是因为刷新用户未设置为级联刷新。在 notificationReceived 映射上设置 CascadeType.REFRESH。

于 2013-09-16T11:31:02.260 回答