关于休眠缓存
场景如下:
我将从数据库中选择一些记录,比如 1000 条记录。然后我将对该结果集执行一些操作,例如在其中再插入一条记录或更新现有记录。
整个上述过程会重复多次,比如2000次。 (即我将再次选择一些记录,但它们不必每次都是完全相同的记录)
我确信我可以使用某种缓存来获得更好的性能。但我不知道怎么办。有人可以指导我吗?
Here is the scenario:
I will select some records from my database, say 1000 records. Then I will do some operations on that result set, like insert one more record in it or update an existing record.
The entire above mentioned process will repeat multiple times, say 2000 times. (i.e. I will again select some records, but they need not be exactly the same records every time)
I am sure that I can use some sort of caching for better performance. But I don't know how. Can someone guide me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当你使用Hibernate时,你实际上使用了两个缓存。第一个是会话缓存。假设您查询 2000 条记录,更新并将更改保存到 5 条,然后再次运行相同的查询(所有这些都在单个会话的范围内)。 Hibernate 实际上不会第二次运行查询 - 它知道您已经将 2000 条记录(和 5 条编辑)加载到内存中。此缓存会自动打开 - 您无法将其关闭,因为它是 Hibernate 核心功能的一部分。您确实需要关闭(或至少刷新)会话以实际确保应用更改 - 您不只是想打开一个巨大的会话并不断更改内容,否则最终您将耗尽内存。
二级缓存基本上在应用程序和数据库之间放置了一个键值存储。该缓存通常寿命较长,多个会话可以使用它,但它也更复杂(例如需要正确处理线程、失效等)。最大的问题是,如果你的数据变化很大,你实际上必须在二级缓存和数据库中进行更改,这可能比直接更改要慢。然而,二级缓存对于只读数据来说非常有用。
调整 Hibernate 和缓存可能非常具有挑战性和复杂性。我强烈建议使用 p6spy 等工具来查看应用程序和数据库之间的数据库流量。
When you use Hibernate, you are actually using two caches. The first is the session cache. Let's say you query 2000 records, update and save changes to 5, and then run the same query again (all in the scope of a single session). Hibernate will not actually run the query a second time - it knows that you have the 2000 records (and the 5 edits) already loaded into memory. This cache is turned on automatically - you can't turn it off, as it's part of Hibernate's core functionality. You do need to close (or at least flush) your session to actually ensure that changes are applied - you don't just want to open one giant session and keep changing things or eventually you will run out of memory.
The second level cache basically puts a key-value store in between your application and the database. This cache is generally longer-lived, and multiple sessions can use it, but it's also more complex (e.g. needs to properly deal with threading, invalidation, etc). The biggest problem is that if your data is changing a lot, you are actually have to make changes both in the second level cache and the database, which can be slower than just making changes directly. The second level cache is fantastic for read-only data, however.
Tuning Hibernate and the caches can be quite challenging and complex. I highly recommend the use of a tool such as p6spy to see the database traffic between your application and the database.
您可以使用 Hibernate 二级缓存。这是一个很好的教程,
http://www.javalobby.org/java/forums/t48846。 html
You can use the Hibernate Second level Cache. Here's a good tutorial,
http://www.javalobby.org/java/forums/t48846.html