- 浏览: 105971 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
u013246812:
谢谢博主帮我解决了问题,就是那个process.exitVal ...
Java执行Shell脚本超时控制 -
fireinjava:
fireinjava 写道配置好多哦 =.=
刚看了下,原来是 ...
Java Spring2.5 Remote Invoke HTTP Invoker -
fireinjava:
配置好多哦 =.=
Java Spring2.5 Remote Invoke HTTP Invoker -
lee79:
呵呵,讲的很对
Java执行Shell脚本超时控制 -
fangwei:
非常感谢!!!btw 你虽然用到了slf4j,却没有用到它的强 ...
Java执行Shell脚本超时控制
Speed Up Your Hibernate Applications with Second-Level Caching
igh-volume database traffic is a frequent cause of performance problems in Web applications. Hibernate is a high-performance, object/relational persistence and query service, but it won't solve all your performance issues without a little help. In many cases, second-level caching can be just what Hibernate needs to realize its full performance-handling potential. This article examines Hibernate's caching functionalities and shows how you can use them to significantly boost application performance.
An Introduction to Caching
Caching is widely used for optimizing database applications. A cache is designed to reduce traffic between your application and the database by conserving data already loaded from the database. Database access is necessary only when retrieving data that is not currently available in the cache. The application may need to empty (invalidate) the cache from time to time if the database is updated or modified in some way, because it has no way of knowing whether the cache is up to date.
Hibernate Caching
Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. This article focuses on second-level cache. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided.
In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects.
Cache Implementations
Caches are complicated pieces of software, and the market offers quite a number of choices, both open source and commercial. Hibernate supports the following open-source cache implementations out-of-the-box:
- EHCache (org.hibernate.cache.EhCacheProvider)
- OSCache (org.hibernate.cache.OSCacheProvider)
- SwarmCache (org.hibernate.cache.SwarmCacheProvider)
- JBoss TreeCache (org.hibernate.cache.TreeCacheProvider)
Each cache provides different capacities in terms of performance, memory use, and configuration possibilities:
- EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory- and disk-based caching. However, it does not support clustering.
- OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
- SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
- JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
Another cache implementation worth mentioning is the commercial Tangosol Coherence cache.
Caching Strategies
Once you have chosen your cache implementation, you need to specify your access strategies. The following four caching strategies are available:
- Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
- Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.
- Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
- Transactional: This is a fully transactional cache that may be used only in a JTA environment.
Support for these strategies is not identical for every cache implementation. Table 1 shows the options available for the different cache implementations.
EHCache | Yes | Yes | Yes | No |
OSCache | Yes | Yes | Yes | No |
SwarmCache | Yes | Yes | No | No |
JBoss TreeCache | Yes | No | No | Yes |
Table 1. Supported Caching Strategies for Hibernate Out-of-the-Box Cache Implementations |
The remainder of the article demonstrates single-JVM caching using EHCache.
Cache Configuration
To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows:
<hibernate-configuration>
<session-factory>
...
<property name="hibernate.cache.provider_class">
org.hibernate.cache.EHCacheProvider
</property>
...
</session-factory>
</hibernate-configuration>
For testing purposes in Hibernate 3, you may also want to use the hibernate.cache.use_second_level_cache property, which allows you to activate (and deactivate) the second-level cache. By default, the second-level cache is activated and uses the EHCache provider.
A Practical Application
Figure 1. The Employee UML Class Diagram |
The sample demo application for this article contains four simple tables: a list of countries, a list of airports, a list of employees, and a list of spoken languages. Each employee is assigned a country, and can speak many languages. Each country can have any number of airports. Figure 1 shows the UML class diagram for the application, and Figure 2 shows the database schema. The sample application source code contains the following SQL scripts, which you need in order to create and instantiate the corresponding database:
- src/sql/create.sql: The SQL script used to create the database.
- src/sql/init.sql: Test data
Note on Installing Maven 2
At the time of writing, the Maven 2 repository seemed to be missing some jars. To get around this problem, find the missing jars in the root directory of the application source code. To install them in the Maven 2 repository, go to the app directory and execute the following instructions:$ mvn install:install-file -DgroupId=javax.security -DartifactId=jacc -Dversion=1.0 -Dpackaging=jar -Dfile=jacc-1.0.jar $ mvn install:install-file -DgroupId=javax.transaction -DartifactId=jta -Dversion=1.0.1B -Dpackaging=jar -Dfile=jta-1.0.1B.jar
Figure 2. The Database Schema |
Setting Up a Read-Only Cache
To begin with something simple, here's the Hibernate mapping for the Country class:
<hibernate-mapping package="com.wakaleo.articles.caching.businessobjects">
<class name="Country" table="COUNTRY" dynamic-update="true">
<meta attribute="implement-equals">true</meta>
<cache usage="read-only"/>
<id name="id" type="long" unsaved-value="null" >
<column name="cn_id" not-null="true"/>
<generator class="increment"/>
</id>
<property column="cn_code" name="code" type="string"/>
<property column="cn_name" name="name" type="string"/>
<set name="airports">
<key column="cn_id"/>
<one-to-many class="Airport"/>
</set>
</class>
</hibernate-mapping>
Suppose you need to display a list of all countries. You could implement this with a simple method in the CountryDAO class as follows:
public class CountryDAO {
...
public List getCountries() {
return SessionManager.currentSession()
.createQuery(
"from Country as c order by c.name")
.list();
}
}
Because this method is likely to be called often, you need to see how it behaves under pressure. So write a simple unit test that simulates five successive calls:
public void testGetCountries() {
CountryDAO dao = new CountryDAO();
for(int i = 1; i <= 5; i++) {
Transaction tx = SessionManager.getSession().beginTransaction();
TestTimer timer = new TestTimer("testGetCountries");
List countries = dao.getCountries();
tx.commit();
SessionManager.closeSession();
timer.done();
assertNotNull(countries);
assertEquals(countries.size(),229);
}
}
You can run this test from either your preferred IDE or the command line using Maven 2 (the demo application provides the Maven 2 project files). The demo application was tested using a local MySQL database. When you run this test, you should get something like the following:
$mvn test -Dtest=CountryDAOTest
...
testGetCountries: 521 ms.
testGetCountries: 357 ms.
testGetCountries: 249 ms.
testGetCountries: 257 ms.
testGetCountries: 355 ms.
[surefire] Running com.wakaleo.articles.caching.dao.CountryDAOTest
[surefire] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 3,504 sec
So each call takes roughly a quarter of a second, which is a bit sluggish by most standards. The list of countries probably doesn't change very often, so this class would be a good candidate for a read-only cache. So add one.
You can activate second-level caching classes in one of the two following ways:
- You activate it on a class-by-class basis in the *.hbm.xml file, using the cache attribute:
<hibernate-mapping package="com.wakaleo.articles.caching.businessobjects"> <class name="Country" table="COUNTRY" dynamic-update="true"> <meta attribute="implement-equals">true</meta> <cache usage="read-only"/> ... </class> </hibernate-mapping>
- You can store all cache information in the hibernate.cfg.xml file, using the class-cache attribute:
<hibernate-configuration> <session-factory> ... <property name="hibernate.cache.provider_class"> org.hibernate.cache.EHCacheProvider </property> ... <class-cache class="com.wakaleo.articles.caching.businessobjects.Country" usage="read-only" /> </session-factory> </hibernate-configuration>
Next, you need to configure the cache rules for this class. These rules determine the nitty-gritty details of how the cache will behave. The examples in this demo use EHCache, but remember that each cache implementation is different.
EHCache needs a configuration file (generally called ehcache.xml) at the classpath root. The EHCache configuration file is well documented on the project Web site. Basically, you define rules for each class you want to store, as well as a defaultCache entry for use when you don't explicitly give any rules for a class.
For the first example, you can use the following simple EHCache configuration file:
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
<cache name="com.wakaleo.articles.caching.businessobjects.Country"
maxElementsInMemory="300"
eternal="true"
overflowToDisk="false"
/>
</ehcache>
This file basically sets up a memory-based cache for Countries with at most 300 elements (the country list contains 229 countries). Note that the cache never expires (the 'eternal=true' property).
Now, rerun the tests to see how the cache performs:
$mvn test -Dtest=CompanyDAOTest
...
testGetCountries: 412 ms.
testGetCountries: 98 ms.
testGetCountries: 92 ms.
testGetCountries: 82 ms.
testGetCountries: 93 ms.
[surefire] Running com.wakaleo.articles.caching.dao.CountryDAOTest
[surefire] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 2,823 sec
As you would expect, the first query is unchanged since the first time around you have to actually load the data. However, all subsequent queries are several times faster.
Behind the Scenes
Before moving on, it is useful to look at what's going on behind the scenes. One thing you should know is that the Hibernate cache does not store object instances. Instead, it stores objects in their "dehydrated" form (to use Hibernate terminology), that is, as a set of property values. The following is a sample of the contents of the Country cache:
{
30 => [bw,Botswana,30],
214 => [uy,Uruguay,214],
158 => [pa,Panama,158],
31 => [by,Belarus,31]
95 => [in,India,95]
...
}
Notice how each ID is mapped to an array of property values. You may also have noticed that only the primitive properties are stored; there is no sign of the airports property. This is because the airports property is actually an association: a set of references to other persistent objects.
By default, Hibernate does not cache associations. It's up to you to decide which associations should be cached, and which associations should be reloaded whenever the cached object is retrieved from the second-level cache.
Association caching is a very powerful functionality. The next section takes a more detailed look at it.
Working with Cached Associations
Suppose you need to display the list of employees (with employee names, languages spoken, etc.) for a given country. The following is the Hibernate mapping of the Employee class:
<hibernate-mapping package="com.wakaleo.articles.caching.businessobjects">
<class name="Employee" table="EMPLOYEE" dynamic-update="true">
<meta attribute="implement-equals">true</meta>
<id name="id" type="long" unsaved-value="null" >
<column name="emp_id" not-null="true"/>
<generator class="increment"/>
</id>
<property column="emp_surname" name="surname" type="string"/>
<property column="emp_firstname" name="firstname" type="string"/>
<many-to-one name="country"
column="cn_id"
class="com.wakaleo.articles.caching.businessobjects.Country"
not-null="true" />
<!-- Lazy-loading is deactivated to demonstrate caching behavior -->
<set name="languages" table="EMPLOYEE_SPEAKS_LANGUAGE" lazy="false">
<key column="emp_id"/>
<many-to-many column="lan_id" class="Language"/>
</set>
</class>
</hibernate-mapping>
Suppose you really need to load the languages spoken by an employee every time you use the Employee object. To force Hibernate to automatically load the languages set, you set the lazy attribute to false. (This is just for the sake of this example. In general, deactivating lazy loading is not a good idea. Do it only when absolutely necessary.) You will also need a DAO class to fetch the employees. The following one would do the trick:
public class EmployeeDAO {
public List getEmployeesByCountry(Country country) {
return SessionManager.currentSession()
.createQuery(
"from Employee as e where e.country = :country "
+ " order by e.surname, e.firstname")
.setParameter("country",country)
.list();
}
}
Next, write some simple unit tests to see how it performs. As in the previous example, you should see how it performs when called repeatedly:
public class EmployeeDAOTest extends TestCase {
CountryDAO countryDao = new CountryDAO();
EmployeeDAO employeeDao = new EmployeeDAO();
/**
* Ensure that the Hibernate session is available
* to avoid the Hibernate initialisation interfering with
* the benchmarks
*/
protected void setUp() throws Exception {
super.setUp();
SessionManager.getSession();
}
public void testGetNZEmployees() {
TestTimer timer = new TestTimer("testGetNZEmployees");
Transaction tx = SessionManager.getSession().beginTransaction();
Country nz = countryDao.findCountryByCode("nz");
List kiwis = employeeDao.getEmployeesByCountry(nz);
tx.commit();
SessionManager.closeSession();
timer.done();
}
public void testGetAUEmployees() {
TestTimer timer = new TestTimer("testGetAUEmployees");
Transaction tx = SessionManager.getSession().beginTransaction();
Country au = countryDao.findCountryByCode("au");
List aussis = employeeDao.getEmployeesByCountry(au);
tx.commit();
SessionManager.closeSession();
timer.done();
}
public void testRepeatedGetEmployees() {
testGetNZEmployees();
testGetAUEmployees();
testGetNZEmployees();
testGetAUEmployees();
}
}
If you run a test using the above configuration, you should get something like the following:
$mvn test -Dtest=EmployeeDAOTest
...
testGetNZEmployees: 1227 ms.
testGetAUEmployees: 883 ms.
testGetNZEmployees: 907 ms.
testGetAUEmployees: 873 ms.
testGetNZEmployees: 987 ms.
testGetAUEmployees: 916 ms.
[surefire] Running com.wakaleo.articles.caching.dao.EmployeeDAOTest
[surefire] Tests run: 3, Failures: 0, Errors: 0, Time elapsed: 3,684 sec
So loading the 50 or so employees assigned to each country takes about a second each time. That's way too slow. This is typical of the N+1 query problem. If you activate the SQL logs, you will see one query on the EMPLOYEE table, followed by literally hundreds of queries on the LANGUAGE table: whenever Hibernate retrieves an employee object from the cache, it reloads all the associated languages. So how can you improve on this? The first thing to do is activate read/write caching on the Employee class as follows:
<hibernate-mapping package="com.wakaleo.articles.caching.businessobjects">
<class name="Employee" table="EMPLOYEE" dynamic-update="true">
<meta attribute="implement-equals">true</meta>
<cache usage="read-write"/>
...
</class>
</hibernate-mapping>
You should also activate caching on the Language class. Read-only caching should do here:
<class name="Language" table="SPOKEN_LANGUAGE" dynamic-update="true">
<meta attribute="implement-equals">true</meta>
<cache usage="read-only"/>
...
</class>
</hibernate-mapping>
Then, you will need to configure the cache rules by adding the following entries to the ehcache.xml file:
<cache name="com.wakaleo.articles.caching.businessobjects.Employee"
maxElementsInMemory="5000"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
/>
<cache name="com.wakaleo.articles.caching.businessobjects.Language"
maxElementsInMemory="100"
eternal="true"
overflowToDisk="false"
/>
This is fine, but it doesn't solve the N+1 query problem: 50 or so extra queries will still be executed whenever you load an Employee. This is a case where you need to activate caching on the language association in the Employee.hbm.xml mapping file, as follows:
<hibernate-mapping package="com.wakaleo.articles.caching.businessobjects">
<class name="Employee" table="EMPLOYEE" dynamic-update="true">
<meta attribute="implement-equals">true</meta>
<id name="id" type="long" unsaved-value="null" >
<column name="emp_id" not-null="true"/>
<generator class="increment"/>
</id>
<property column="emp_surname" name="surname" type="string"/>
<property column="emp_firstname" name="firstname" type="string"/>
<many-to-one name="country"
column="cn_id"
class="com.wakaleo.articles.caching.businessobjects.Country"
not-null="true" />
<!-- Lazy-loading is deactivated to demonstrate caching behavior -->
<set name="languages" table="EMPLOYEE_SPEAKS_LANGUAGE" lazy="false">
<cache usage="read-write"/>
<key column="emp_id"/>
<many-to-many column="lan_id" class="Language"/>
</set>
</class>
</hibernate-mapping>
In this configuration, you should get near-optimal performance:
$mvn test -Dtest=EmployeeDAOTest ... testGetNZEmployees: 1477 ms. testGetAUEmployees: 940 ms. testGetNZEmployees: 65 ms. testGetAUEmployees: 65 ms. testGetNZEmployees: 76 ms. testGetAUEmployees: 52 ms. [surefire] Running com.wakaleo.articles.caching.dao.EmployeeDAOTest [surefire] Tests run: 3, Failures: 0, Errors: 0, Time elapsed: 0,228 sec
To do this, you need to set the hibernate.cache.use_query_cache property in the hibernate.cfg.xml file to true, as follows:
<property name="hibernate.cache.use_query_cache">true</property>
Then, you use the setCacheable() method as follows on any query you wish to cache:
public class CountryDAO {
public List getCountries() {
return SessionManager.currentSession()
.createQuery("from Country as c order by c.name")
.setCacheable(true)
.list();
}
}
To guarantee the non-staleness of cache results, Hibernate expires the query cache results whenever cached data is modified in the application. However, it cannot anticipate any changes made by other applications directly in the database. So you should not use any second-level caching (or configure a short expiration timeout for class- and collection-cache regions) if your data has to be up-to-date all the time.
Proper Hibernate Caching
Caching is a powerful technique, and Hibernate provides a powerful, flexible, and unobtrusive way of implementing it. Even the default configuration can provide substantial performance improvements in many simple cases. However, like any powerful tool, Hibernate needs some thought and fine-tuning to obtain optimal results, and caching—like any other optimization technique—should be implemented using an incremental, test-driven approach. When done correctly, a small amount of well executed caching can boost your applications to their maximum capacities.- 14239.rar (351.9 KB)
- 下载次数: 15
发表评论
-
Spring声明式事务管理与配置详解
2015-08-18 09:00 01、Spring声明式事务配置的五种方式 前段时间对 ... -
Log4j的配置与使用详解
2015-08-18 08:44 7711、介绍 Log4j是Apache的一个开放源代码项目 ... -
Web.xml
2015-08-18 08:35 436web.xml文件详解 前言:一般的 ... -
Spring Filter
2015-08-18 08:23 5111、简介 Filter也称 ... -
springSecurity源码分析——DelegatingFilterProxy类的作用
2014-12-16 13:56 701http://www.cnblogs.com/hzhu ... -
spring data jpa 中的OpenEntityManagerInViewFilter 取代OpenSessionInViewFilter
2014-12-05 13:52 0http://blog.csdn.net/lzwglory/ ... -
servlet tomcat web.xml配备信息说明
2014-12-05 13:50 0servlet tomcat web.xml配置信息说明 ... -
Spring IntrospectorCleanupListener
2014-12-05 12:40 660spring中提供了一个名为 org.springfr ... -
Spring IOC容器实例化Bean的方式与RequestContextListener应用
2014-12-05 12:35 1069spring IOC容器实例化Be ... -
SpringBean的5种作用域
2014-12-05 12:33 796org.springframework.web.contex ... -
Lobback日志文件
2014-12-05 12:29 1178Logback是由log4j创始人Ceki Gülcü设计的 ... -
HTML Element
2012-08-05 17:16 9631. select 1) Clear Select O ... -
Prototype Study (转)
2012-08-05 16:49 806什么是Prototype Prototype 是由 S ... -
Prototype Element
2012-08-05 16:46 9291. select <select name=&q ... -
IE Firefox 一些组件的特殊处理
2012-07-29 09:04 8751、html alt 在IE下控件的alt属性使用赋值后,当 ... -
log4j 自动生成 appender
2011-05-04 21:55 1670一般log4j的配置是通过log4j.properties或x ... -
Java ASP Post
2011-03-06 20:32 1187用Java编写的模拟ASP Post请求写的一个上海的违章查询 ... -
Java Spring2.5 Remote Invoke HTTP Invoker
2011-03-06 20:16 2691近日,一个项目涉及到 ... -
Java Spring1.2 Remote Invoke HTTP Invoker
2011-02-25 09:12 1309近日,一个项目涉及到系统间接口调用,考虑到系统间用的都是jav ... -
File Encoding Converter
2009-11-13 16:52 1694在Java应用开发中,经常会遇到不同的开发人员的IDE设置的文 ...
相关推荐
它位于Hibernate应用和数据库之间,减少了对数据库的直接访问,通过存储数据库数据的副本来加速数据检索。 **1. Hibernate缓存概述** Hibernate缓存主要分为一级缓存和二级缓存。一级缓存是Session级别的,而二级...
Hibernate支持多级缓存管理机制,包括一级缓存和二级缓存。 #### 二、缓存范围 缓存范围定义了缓存的生命周期以及哪些组件能够访问它。根据不同的应用场景,Hibernate支持三种缓存范围: 1. **事务范围缓存**:...
开启hibernate.generate.statistics可获取统计信息,帮助分析实体、集合、会话和二级缓存的行为。 此外,文章还提到了监控SQL生成以揭示潜在性能问题,以及利用Hibernate统计信息进行诊断。不过,由于篇幅限制,...
- 在Hibernate配置中指定使用hibernate-memcached作为二级缓存。 - 如果单独使用Spring,需要配置Spring的缓存管理器,并关联xmemcache-spring的相关配置。 - 在需要缓存的方法上使用Spring的缓存注解。 8. **...
- **缓存策略:** 使用一级缓存(Session级)和二级缓存(SessionFactory级)减少数据库交互。 - **批处理:** 批量操作可以减少数据库调用次数,提高性能。 - **连接池:** 配置连接池,如C3P0或Apache DBCP,有效...
Hibernate提供了多种性能优化手段,包括预加载(Eager Loading)、批处理(Batch Processing)、二级缓存和缓存配置等。根据项目需求和性能指标,进行适当调整能大幅提升系统性能。 总之,Hibernate中文帮助文档...
关于Hazelcast-Hibernate3的使用,开发者可以将Hazelcast作为二级缓存来加速数据的读取,减少数据库的负载。通过配置,可以指定哪些实体或属性应该被缓存,以及缓存策略(如时间过期、容量限制等)。此外,Hazelcast...
本压缩包"EHCache插件.rar"提供了将EHCache集成到Hibernate二级缓存中的相关组件和配置文件,使得数据库操作可以通过缓存来加速,降低对数据库的直接访问,从而提高系统响应速度。 **一、Hibernate二级缓存** 在...
- **二级缓存**:使用Redis作为二级缓存,负责存储更大量的数据和备份Ehcache中的数据。 这种设计模式不仅能够有效降低数据库的压力,还能提高系统的响应速度和吞吐量。 #### 八、结论 通过本文的介绍,我们了解...
Hibernate Memcached是将Memcached作为二级缓存机制引入到Hibernate中的一个插件,它允许开发者将频繁访问的数据存储在内存缓存中,以提高应用的响应速度。Hibernate Memcached 1.1.0版提供了完整的API文档和...
此外,Hibernate还支持二级缓存,提高数据访问速度。 Oracle数据库以其稳定性、安全性以及高性能著称,尤其适合大型企业级应用。在SpringMVC和Hibernate的配合下,Oracle可以提供可靠的数据存储和复杂查询功能。...
7. **缓存机制**:Hibernate支持一级缓存(Session级别的缓存)和二级缓存(SessionFactory级别的缓存)。缓存可以提高数据读取速度,减少对数据库的访问,但需要正确管理以避免数据一致性问题。 8. **事务管理**:...
- **二级缓存**:使用 Ehcache 或 Memcached 实现二级缓存,提高数据读取速度。 - **延迟加载**:避免不必要的懒加载,减少 N+1 查询问题。 - **关联优化**:优化一对多、多对一等关联映射,使用 eager/lazy ...
为了保证系统的稳定性和性能,我们还进行了适当的优化措施,例如使用二级缓存提高数据读取速度,通过预编译SQL语句(PreparedStatement)防止SQL注入,以及合理设计数据库索引以加速查询。 总的来说,通过Hibernate...
- **ORM(Hibernate,Toplink)缓存**:ORM框架通常内置了一级缓存和二级缓存机制,以减少对数据库的访问次数。 - **数据库层的缓存**:在数据库级别进行缓存,如使用MySQL的Query Cache。 - **业务对象的缓存**:...
Hibernate支持二级缓存,它可以缓存经常访问的数据,减少对数据库的直接访问。在登录模块,用户信息可能会被缓存,以加速登录验证过程。 7. **模块控制**: 项目的模块化设计有助于代码的管理和维护。在这个项目中...
为了提高数据访问效率,Hibernate引入了一系列性能优化措施,如二级缓存、批量加载和延迟加载。其中,批量加载和延迟加载尤其有助于减少数据库交互次数,提高应用响应速度。 ### 正向工程与反向工程 在Hibernate中...