无法使用 Hibernate EntityManager 绕过缓存

Impossible to bypass caches with Hibernate EntityManager

我的代码有问题吗?如果不重新启动应用程序,我无法检索我的 User 实体上的更改。

这是我的 persistence.xml:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
             http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="pu" transaction-type="RESOURCE_LOCAL">
    <properties>
        <property name = "hibernate.show_sql" value = "true" />
    </properties>
</persistence-unit>

</persistence>

我这样创建 EntityManagerFactory

public static EntityManagerFactory entityManagerFactory(String driver, String url, String user, String password, DataSource datasource) {
    LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();

    DBPoolDataSource dataSource = new DBPoolDataSource();

    dataSource.setName("pool-ds");
    dataSource.setDescription("Pooling DataSource");
    dataSource.setDriverClassName(driver);
    dataSource.setUrl(url);
    dataSource.setUser(user);
    dataSource.setPassword(password);
    dataSource.setMinPool(5);
    dataSource.setMaxPool(10);
    dataSource.setMaxSize(30);
    dataSource.setIdleTimeout(3600);
    dataSource.setValidationQuery("SELECT id FROM test");

    entityManagerFactory.setDataSource(datasource);
    entityManagerFactory.setPersistenceUnitName("pu");
    entityManagerFactory.setJpaDialect(new HibernateJpaDialect());
    entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    Map<String, Object> props = entityManagerFactory.getJpaPropertyMap();
    props.put("hibernate.cache.use_second_level_cache", "false");
    props.put("hibernate.cache.use_query_cache", "false");

    entityManagerFactory.afterPropertiesSet();

    return entityManagerFactory.getObject();
}

这是我的实体:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "USER")
public class User {

    @Id
    private String trigram;

    @Column(name = "FIRST_NAME")
    private String firstName;

    @Column(name = "LAST_NAME")
    private String lastName;

    public String getTrigram() {
        return trigram;
    }

    public void setTrigram(String trigram) {
        this.trigram = trigram;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (!trigram.equals(user.trigram)) return false;
        if (firstName != null ? !firstName.equals(user.firstName) : user.firstName != null) return false;
        return lastName != null ? lastName.equals(user.lastName) : user.lastName == null;
    }

    @Override
    public int hashCode() {
        int result = trigram.hashCode();
        result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
        result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
        return result;
    }
}

这是我的存储库:

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;

public class UserDao {

    private EntityManager entityManager;

    public UserDao(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public User getByTrigram(String trigram) throws NoResultException {

        entityManager.getEntityManagerFactory().getCache().evictAll();

        TypedQuery<User> q = entityManager.createQuery(
                "select u from User u where u.trigram = :trigram", User.class);
        q.setParameter("trigram", trigram);
        q.setHint("javax.persistence.cache.retrieveMode", CacheRetrieveMode.BYPASS);
        return q.getSingleResult();
    }
}

-> 所以实体不是来自 L1.

entityManagerFactory.getJpaPropertyMap() 包含:

-> 所以应该没有 L2 也没有来自查询缓存。

但是,直接在我的数据库中所做的更改只有在重新启动后才会被我的存储库检索。

有人有想法吗? 谢谢!

默认情况下,Hibernate 4 已经禁用了二级缓存和查询缓存,所以配置hibernate.cache.use_second_level_cache=falsehibernate.cache.use_query_cache=fals没有用。

实体缓存在hibernate Session(L1)中,如果要根据底层数据库刷新这个特定的实体,可以创建这样的方法:

public void refresh(User user) {
    org.hibernate.Session session = entityManager.unwrap(Session.class);
    session.refresh(user);
}

并在检索到用户后调用它,这样:

User currentUser = userDao.getByTrigram(login);
userDao.refresh(currentUser);

希望对您有所帮助!