为什么不从二级缓存加载持久化实体?

时间:2014-06-10 14:17:55

标签: java hibernate ehcache

hibernate是否会使用save方法存入二级缓存实体?

我的代码是:

Session session = sessionFactory.openSession();

        Transaction transaction = session.beginTransaction();

        Person person = new Person("Volodia", "Levytskyi", "Mykolaiv");
        session.save(person);
        transaction.commit();
        session.close();

        session = sessionFactory.openSession();
        transaction = session.beginTransaction();

        Person load = (Person) session.load(Person.class, (long) 1);
        System.out.println("load2=" + load);
        transaction.commit();
        session.close();

我希望hibernate从二级缓存人员加载,但是当

时它会向数据库发出select查询
session.load(Person.class, (long) 1);

正在运行。

我的hibernate.cfg.xml:

<session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernateSimpleDB</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"></property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="transaction.factory_class">org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory</property>

        <property name="hibernate.hbm2ddl.auto">create</property>

        <property name="hibernate.cache.use_second_level_cache">true</property>

        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
        <property name="hibernate.generate_statistics">true</property>

        <property name="current_session_context_class">thread</property>

        <mapping resource="com/masterhibernate/SimpleHibernateDemo/Person.hbm.xml" 
            />

        <!-- <mapping class="com.masterhibernate.SimpleHibernateDemo.Person" /> -->
    </session-factory>
</hibernate-configuration>

我的Person.hbm.xml:

<hibernate-mapping>
    <class name="com.masterhibernate.SimpleHibernateDemo.Person"
        table="Person">
        <cache usage="read-write" />

        <id name="id" column="PersonId">
            <generator class="native" />
        </id>
        <property name="name">
            <column name="name" length="16" not-null="true" />
        </property>
        <property name="surname">
            <column name="surname" length="36"></column>
        </property>
        <property name="address">
            <column name="address" length="22"></column>
        </property>
    </class>
</hibernate-mapping>

为什么会这样?

1 个答案:

答案 0 :(得分:4)

您似乎已将数据库设置为为您生成主键。这意味着,当您保存实体时,它还没有ID,因为稍后将由数据库分配。这也意味着hibernate不能将它存储在二级缓存中,因为它还没有用它来索引它的密钥。它应该在从数据库中再次检索后存储在二级缓存中。