JPA同步问题,需要重启应用程序

时间:2016-12-15 22:15:32

标签: java mysql hibernate jpa

我已经创建了一个应用程序,其中我的所有数据库查询都是使用JPA完成的。我有一个方法,我编辑一列,下面添加代码;

public static void setReservationAsUnactive(Reservation obj) {
    em.getTransaction().begin();

    obj.setActive(0);
    obj.setReturnedDate(new Date());
    em.merge(obj);

    em.getTransaction().commit();
}

我可以看到我的mysql数据库中的列已正确更改,但是当我尝试在JPA查询中将其拉出时,更改不存在,但是 - 当我重新启动应用程序时,更改是我...如何确保我提取的数据是新数据而不是某些缓存?

3 个答案:

答案 0 :(得分:1)

您需要从缓存中逐出对象

em.getEntityManagerFactory().getCache().evict(theClass, thePrimaryKey);

其他解决方案是删除缓存存储(对我来说是错误的解决方案)。 Guide for disabling the cache storage

以下是documentation of the cache and how is stored in JPA

答案 1 :(得分:1)

尝试通过em.refresh(obj);

从基础数据库中获取您的实体

请告知您是否缓存实体经理?

答案 2 :(得分:0)

感谢您的反馈。但是我通过从最初从中检索它来获取对象来解决它。

示例:

// this will work, and it will update the database, but the user need to restart his client to view the edited row
public void btnSetReservationToUnactive() {
    TableObject tableObject = getSelectedObject();
    ReservationBean.setReservationAsUnactive(ReservationBean.getReservationByID(tableObject.getID()));

}

// this method will update the current clients view also, because it get the object were it originally came from.
// rather than getting a new object from the em.
public void btnSetReservationToUnactive() {
    TableObject tableObject = getSelectedObject();
    ReservationBean.setReservationAsUnactive(getReservationByIdFromTable(tableObject.getID()));

}

public Reservation getReservationByIdFromTable(int resID) {
    for (Reservation res : customer.getReservationCollection()){
        if (res.getID() == resID)
            return res;
    }

}