<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Hibernate EhCache 配置教程 > 原文: [https://howtodoinjava.com/hibernate/hibernate-ehcache-configuration-tutorial/](https://howtodoinjava.com/hibernate/hibernate-ehcache-configuration-tutorial/) 緩存是 ORM 框架提供的功能,可幫助用戶獲得快速運行的 Web 應用,同時幫助框架本身減少在單個事務中對數據庫的查詢數量。 [**Hiberate**](//howtodoinjava.com/hibernate-tutorials/ "hibernate tutorials") 還在兩層中提供了此緩存功能。 * **一級緩存**:默認情況下啟用,并在會話范圍內工作。 閱讀有關 [**Hiberate 一級緩存**](//howtodoinjava.com/hibernate/understanding-hibernate-first-level-cache-with-example/ "Understanding hibernate first level cache with example")的更多信息。 * **二級緩存**:與一級緩存不同,后者可以在會話工廠范圍內全局使用。 在本教程中,我將給出一個使用 ehcache 配置作為 Hiberate 中的[**二級緩存的示例**](//howtodoinjava.com/hibernate/how-hibernate-second-level-cache-works/ "How hibernate second level cache works?")。 ![Hibernate with EhCache](https://img.kancloud.cn/a4/c6/a4c6b13a09e298bdc96dc0c58f20f87d_392x129.png) Hibernate 和 EhCache ```java Sections in this post: How second level cache works About EhCache Configuring EhCache Configuring entity objects Query caching Example application 源碼下載 ``` ## 二級緩存的工作方式 讓我們逐點寫下所有事實: 1. 每當 Hiberate 會話嘗試加載實體時,它首先會在一級緩存(與特定的 Hiberate 會話關聯)中尋找實體的緩存副本。 2. 如果一級高速緩存中存在實體的高速緩存副本,則將其作為裝入方法的結果返回。 3. 如果第一級高速緩存中沒有高速緩存的實體,則在第二級高速緩存中查找高速緩存的實體。 4. 如果二級緩存已緩存實體,則將其作為裝入方法的結果返回。 但是,在返回實體之前,它也存儲在第一級緩存中,以便對實體的加載方法的下一次調用將從第一級緩存本身返回該實體,而無需再次進入第二級緩存。 5. 如果在一級緩存和二級緩存中均未找到實體,則在作為`load()`方法的響應返回之前,將執行數據庫查詢并將實體存儲在兩個緩存級別中。 6. 如果已通過 Hiberate 會話 API 完成了修改,則二級緩存會針對修改后的實體進行自我驗證。 7. 如果某些用戶或進程直接在數據庫中進行更改,則直到該緩存區域的“`timeToLiveSeconds`”持續時間過去之后,二級緩存才能更新自身。 在這種情況下,最好使整個緩存無效,然后讓 Hiberate 再次構建其緩存。 您可以使用下面的代碼片段使整個 Hiberate 二級緩存無效。 ## 關于 EhCache Terracotta Ehcache 是??一種流行的開源 Java 緩存,可以用作 Hibernate 二級緩存。 它可以用作獨立的二級緩存,也可以配置為群集以提供復制的相干二級緩存。 Hibernate 隨附 ehcache 庫。 如果需要任何特定版本的 ehcache,請訪問 Terracotta **Ehcache 下載站點**: [http://www.terracotta.org/products/enterprise-ehcache](http://www.terracotta.org/products/enterprise-ehcache) **maven 依賴項**適用于 Ehcache 2.0,并且任何升級都是: ```java <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>[2.0.0]</version> <type>pom</type> </dependency> ``` ## 配置 EhCache 要配置 ehcache,您需要執行兩個步驟: 1. 配置 Hibernate 進行二級緩存 2. 指定二級緩存供應器 **Hibernate 4.x 及更高版本** ```java <property key="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> ``` **Hibernate 3.3 及更高版本** ```java <property key="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property> ``` **Hibernate 3.2 及更低版本** ```java <property key="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.region.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property> ``` ## 配置實體對象 這可以以兩種方式完成。 1)如果您正在使用`hbm.xml`文件,請使用以下配置: ```java <class name="com.application.entity.DepartmentEntity" table="..."> <cache usage="read-write"/> </class> ``` 2)否則,如果您使用的是注解,請使用以下**注解**: ```java @Entity @Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="department") public class DepartmentEntity implements Serializable { //code } ``` 對于這兩個選項,**緩存策略**可以具有以下類型: * **`none`**:不進行緩存。 * **`readonly`**:如果您的應用需要讀取而不是修改持久類的實例,則可以使用只讀緩存。 * **`read-write`**:如果應用需要更新數據,則可能需要讀寫緩存。 * **`nonstrict-read-write`** :如果應用僅偶爾需要更新數據(即,如果兩個事務很難同時嘗試更新同一項目,則非常不可能),并且不需要嚴格的事務隔離 非嚴格讀寫緩存可能是合適的。 * **`transactional`** :事務緩存策略為完全事務緩存供應器(例如 JBoss TreeCache)提供支持。 這樣的緩存只能在 JTA 環境中使用,并且必須指定 `hibernate.transaction.manager_lookup_class`。 ## 查詢緩存 您還可以啟用查詢緩存。 為此,請在`hbm.xml`中進行配置: ```java <property key="hibernate.cache.use_query_cache">true</property> ``` 以及在代碼中定義查詢的位置,將方法調用`setCacheable(true)`添加到應緩存的查詢中: ```java sessionFactory.getCurrentSession().createQuery("...").setCacheable(true).list(); ``` 默認情況下,Ehcache 將為您配置用于緩存的每個實體創建單獨的緩存區域。 您可以通過將配置添加到`ehcache.xml`中來更改這些區域的默認值。 要提供此配置文件,請在 Hiberate 配置中使用以下屬性: ```java <property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property> ``` 并使用以下配置覆蓋默認配置: ```java <cache name="com.somecompany.someproject.domain.Country" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" /> ``` 請注意,在`ehcache.xml`中,如果`eternal="true"`,那么我們不應編寫`timeToIdealSeconds`和`timeToLiveSeconds`,hibernate 會注意這些值 。因此,如果要手動提供值,最好始終使用`eternal=”false”`,以便我們可以手動將值分配給`timeToIdealSeconds`和`timeToLiveSeconds`。 `timeToIdealSeconds="seconds"`表示,如果全局緩存中的對象是理想的,則表示不被任何其他類或對象使用,那么它將等待一段時間,我們指定了該時間,如果時間已從全局緩存中刪除 超過了`timeToIdealSeconds`值。 `timeToLiveSeconds="seconds"`表示另一個`Session`或類是否使用此對象,我的意思是它是否正在被其他會話使用,無論情況如何,一旦度過了`timeToLiveSeconds`指定的時間,然后它將被 Hiberate 從全局緩存中刪除。 ## 示例應用 在我們的示例應用中,我有一個`DepartmentEntity`,我想使用 ehcache 啟用二級緩存。 讓我們逐步記錄更改: **1)hibernate.cfg.xml** ```java <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedemo</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">create</property> <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <mapping class="hibernate.test.dto.DepartmentEntity"></mapping> </session-factory> </hibernate-configuration> ``` **2)`DepartmentEntity.java`** ```java package hibernate.test.dto; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity (name = "dept") @Table(name = "DEPARTMENT", uniqueConstraints = { @UniqueConstraint(columnNames = "ID"), @UniqueConstraint(columnNames = "NAME") }) @Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="department") public class DepartmentEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID", unique = true, nullable = false) private Integer id; @Column(name = "NAME", unique = true, nullable = false, length = 100) private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` **3)`HibernateUtil.java`** ```java package hibernate.test; import java.io.File; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new AnnotationConfiguration().configure(new File("hibernate.cgf.xml")).buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } } ``` **4)`TestHibernateEhcache.java`** ```java public class TestHibernateEhcache { public static void main(String[] args) { storeData(); try { //Open the hibernate session Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); //fetch the department entity from database first time DepartmentEntity department = (DepartmentEntity) session.load(DepartmentEntity.class, new Integer(1)); System.out.println(department.getName()); //fetch the department entity again; Fetched from first level cache department = (DepartmentEntity) session.load(DepartmentEntity.class, new Integer(1)); System.out.println(department.getName()); //Let's close the session session.getTransaction().commit(); session.close(); //Try to get department in new session Session anotherSession = HibernateUtil.getSessionFactory().openSession(); anotherSession.beginTransaction(); //Here entity is already in second level cache so no database query will be hit department = (DepartmentEntity) anotherSession.load(DepartmentEntity.class, new Integer(1)); System.out.println(department.getName()); anotherSession.getTransaction().commit(); anotherSession.close(); } finally { System.out.println(HibernateUtil.getSessionFactory().getStatistics().getEntityFetchCount()); //Prints 1 System.out.println(HibernateUtil.getSessionFactory().getStatistics().getSecondLevelCacheHitCount()); //Prints 1 HibernateUtil.shutdown(); } } private static void storeData() { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); DepartmentEntity department = new DepartmentEntity(); department.setName("Human Resource"); session.save(department); session.getTransaction().commit(); } } Output: Hibernate: insert into DEPARTMENT (NAME) values (?) Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=? Human Resource Human Resource Human Resource 1 1 ``` 在上面的輸出中,第一次從數據庫中獲取部門。 但接下來的兩次是從緩存中提取的。 最后一次獲取來自二級緩存。 要下載上述應用的源代碼,請點擊以下鏈接。 [源碼下載](https://docs.google.com/file/d/0B7yo2HclmjI4eWpOYmZReWRvcEk/edit?usp=sharing "hibernate ehcache demo source code") 希望你喜歡上面的文章。 如果您有任何問題或建議,請發表評論。 **祝您學習愉快!** **參考** [http://www.ehcache.org/documentation/user-guide/hibernate](http://www.ehcache.org/documentation/2.8/hibernate/) [https://community.jboss.org/wiki/ConfigureEhcacheAsASeecondLevelCache](https://community.jboss.org/wiki/ConfigureEhcacheAsASecondLevelCache)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看