休眠是否将保存到使用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();
我希望休眠从第二级缓存人员加载,但是在以下情况下它会向数据库发出选择查询
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>
为什么是这样?
最佳答案
好像您已设置数据库来为您生成主键。这意味着,当您保存实体时,它还没有ID,因为它将在以后由数据库分配。这也意味着休眠无法将其存储在二级缓存中,因为它尚无用于对其进行索引的键。但是,应再次从数据库中检索它后,将其存储在二级缓存中。