As the data is read, Hibernate puts the contents of the first read into the cache, if the other application modifies the data in the database, when the program reads again, the content is directly fetched from the cache and does not reflect the latest state in the database.
Therefore, you can set the mode of reading data, without reading the cache, read from the database directly, the method is as follows:
Public List queryobjectsbyhql (String hql, Boolean queryfromcache) throws Hibernateexception
{
Session session = GetSession ();
List List = null;
Try
{
Query query = session.createquery (HQL);
Set to Cachemode.ignore mode, when reading data, do not exchange data with the cache, directly read the database.
This method only modifies the query mode of this session
if (!queryfromcache)
{
Query.setcachemode (Cachemode.ignore);
}
List = Query.list ();
}
catch (Exception e)
{
SYSTEM.OUT.PRINTLN ("Query failed:" + e.getmessage ());
}
Finally
{
Session.close ();
}
return list;
}
Hibernate read Database Cache issues
Hibernate uses a level two cache strategy, which works as follows:
1) When a condition is queried, always issue a SELECT * FROM table_name where ... to get all the data objects at once.
2) Put all the obtained data objects into the second level cache based on the ID.
3) When hibernate accesses the data object according to the ID, it is first checked from the session cache, and if the level two cache is configured, it is checked from the level two cache, and the database is not found, and the result is placed in the cache by ID.
4) Update the cache while deleting, updating, and adding data.
Since hibernate is based on the ID in the level two cache first search, when inserting or deleting the ID has changed, so the data can be updated timely, and update the database because the same ID in the cache can still be found, so read again to the level two cache shutdown. The specific steps are:
1) dao.getsession (). Clear ();//first-level cache cleared
2) Query.setcachemode (Cachemode.ignore); Turn off level two cache