使用Hibernate EntityManager

时间:2017-11-17 18:14:41

标签: java hibernate caching 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();
    }
}

- &GT;所以实体不是来自L1

entityManagerFactory.getJpaPropertyMap()包含:

  • hibernate.cache.use_second_level_cache=false
  • hibernate.cache.use_query_cache=false

- &GT;所以不应该有L2,也不应该来自查询缓存。

但是,直接在我的数据库中进行的更改仅在重新启动后由我的存储库检索。

有人有想法吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

默认情况下,Hibernate 4已禁用L2缓存和查询缓存,因此配置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);

希望它有所帮助!