能否禁用Hibernate中的一级缓存?若可以该如何操作?
Hey there! Let's tackle your two questions about Hibernate's first-level cache (also called the session cache) one by one.
1. 能不能禁用Hibernate的一级缓存?
Short answer: Yes, you can effectively disable or bypass it, though it's important to note that the first-level cache is a core part of Hibernate's Session design—it's meant to reduce database hits and ensure consistency within a single session. But if your use case (like bulk data processing, or needing fresh data every time) requires avoiding it, there are reliable ways to do so.
2. 具体操作方式
Here are the most common and practical methods to disable/bypass the first-level cache:
Use a
StatelessSessioninstead of a regularSession
This is the most straightforward way to completely avoid the first-level cache. AStatelessSessionis a lightweight, non-caching session that doesn't track entity state or maintain any cache. It's perfect for bulk inserts/updates/deletes where you don't need session-level consistency and want to minimize memory usage.
Example code:SessionFactory sessionFactory = // 获取你的SessionFactory实例 try (StatelessSession statelessSession = sessionFactory.openStatelessSession()) { // 执行你的数据库操作,比如批量插入 for (Entity entity : largeEntityList) { statelessSession.insert(entity); } }Set
CacheMode.IGNOREfor specific operations
If you still want to use a regularSessionbut need to bypass the cache for certain queries, you can set theCacheModetoIGNORE. This tells Hibernate not to read from the first-level cache for the operation, and also not to store the results in the cache.
Example with HQL:try (Session session = sessionFactory.openSession()) { List<Entity> entities = session.createQuery("FROM Entity WHERE status = :status", Entity.class) .setParameter("status", "ACTIVE") .setCacheMode(CacheMode.IGNORE) .list(); }Manually clear or evict cache entries
If you need to keep using a regularSessionbut want to remove specific entities or the entire cache, you can use these methods:session.evict(entity): Removes a single entity from the first-level cache. Useful when you know a specific entity's data has changed in the database and you don't want the cached version.session.clear(): Clears all entities from the first-level cache. Use this if you want to start fresh with no cached data in the current session.
Use
session.refresh(entity)to force fresh data
If you already have an entity in the cache but need the latest version from the database, callingsession.refresh(entity)will reload the entity directly from the database, overwriting the cached version. This isn't exactly "disabling" the cache, but it ensures you get up-to-date data when you need it.
内容的提问来源于stack exchange,提问作者kavya

