But do not create a new sessionfactory only for the service and a request, because
Creating sessionfactory consumes a lot of resources.And then create Session object session = factory. opensession () based on sessionfactory ();
Transaction Ts = NULL;
Try {
TS = session. begintransaction (); // start a transaction
...................... // Execute the transaction
TS. Commit (); // submit the transaction
} Catch (hibernateexception e) {// undo the transaction if an exception occurs.
If (TS! = NULL ){
TS. rollback (); // roll back the transaction
}
E. printstacktrace ();
} Finally {
Session. Close (); // no matter whether the transaction is successfully executed or not, close the session and put it in finally to improve security.
}
Next we will focus on session-level caching.
The Hibernate cache is divided into two levels. The first level is stored in the session, which is called the first level cache. It is carried by default and cannot be detached.
Because the life cycle of a session is usually very short, the life cycle of the fastest cache in the session is also very short, so the hit rate of the first cache is very low. Its Improvements to system performance are also limited. Of course, this
Items
Session
Internal cache is mainly used to maintain
Session
Internal data status Synchronization. Not provided by hibernate to greatly improve system performance.
To improve the performance of hibernate, in addition to some common methods that require attention, such as using delayed loading, urgent external connections, and query filtering, you also need to configure the level-2 cache of hibernate. The improvements to the overall system performance are often immediate ..
ApplicationThe first-level cache of Hibernate is provided by the session, so it only exists in the session lifecycle. When the program calls save (), update (), saveorupdate () when you call the query interface list, filter, or iterate, for example, the session cache does not contain the corresponding object,
Hibernate will add this object to the first-level cache.,
When the session is closed, the level-1 cache managed by the session will be cleared immediately.
The Hibernate level-1 cache is built in the session and cannot be uninstalled or configured.
The primary cache uses the key-value map method. When the object is cached, the primary key ID of the object is the key of the map, and the object is the corresponding value. So,A level-1 cache is stored as entity objects.The primary keyword ID is used during access.
Although hibernate uses automatic maintenance and does not provide any configuration functions for the level-1 cache, manual intervention can be performed on the management of the level-1 cache through the methods provided in the session. The following two intervention methods are provided in session:
● Evict (): Used to clear an object from the session cache.
The evict () method is applicable to the following two situations:
1) No need to update the synchronized data of this object
2) during batch update and deletion, after each object is deleted, the memory occupied by this object must be released.
● Clear (): Used to clear all objects in the first-level cache.
During one-time update of large batches of data, a large amount of memory is used to cache updated objects. In this case, the clear () method should be called periodically to clear the objects in the first-level cache and control the size of the first-level cache to avoid memory overflow.
How to handle cache when Hibernate is updated in batches:
(Assume that the age in our user table has 5000 records greater than 0.) Session session = sessionfactory. opensession ();
Transaction Tx = session. begintransaction ();
Itertaor users = session. Find ("from user u where u. age> 0"). itertaor (); // The HSL statement will not be explained.
While (user. hasnext ()){
User user = (User) users. Next ();
User. setage (user. getage () + 1 );
// Write the inserted objects in this batch to the database immediately and release the memory.
Session. Flush ();
Session. Clear ();
}
TX. Commit ();
Session. Close ();
When you use hibernate to process a large number of data, you must first execute the 5000 update statement before updating the 5000 user objects ..
This affects the performance of the operation... when we encounter performance and space problems in the project, the performance should be the primary... this is to sacrifice space.
So it is better for the program to skip the hibernate API and directly execute it through the jdbc api...
Let's change the above Code: Session session = sessionfactory. opensession ();
Transaction Tx = session. begintransaction ();
Connection conn = session. Connection ();
Preparedstatement pstmt = conn. preparestatement ("Update users set age = age + 1" + "where age> 0 ");
Pstmt.exe cuteupdate ();
TX. Commit ();
Although this is through the jdbc api, it is essentially through the interface of hibernater transaction to declare the transaction boundary...
In fact, the best solution is to create a stored procedure and run it with the underlying database. This provides good performance and high speed ....
I will simply take the Oracle database as an example. Create a stored procedure named userupdate... and then call it in the program...
The Stored Procedure Code of userupdate:
Create or replace procadure userupdate (u_age in number)
Begin
Update users set age = age + 1 where age> u_age;
End;
The following describes how to call our named stored procedure in a program.
Session session = sessionfactory. opensession ();
Transaction Tx = session. begintransaction ();
Connection conn = session. Connection ();
String STR = "{call userupdate (?)} ";
Callablestatement cstmt = conn. preparecall (STR );
Cstmt. setint (1, 0 );
Cstmt.exe cuteupdate ();
TX. Commit ();
Note: open-source MySQL does not support stored procedures ..
The advantage of using jdbc apis is that ..
It does not need to load a large amount of data into the memory in advance, and then update and modify it... so it will not consume a large amount of memory ....
(There is no difference in the small program .. when the data record reaches a certain amount of data, it will naturally find the difference between the hibernate API and the jdbc api)
Only one record can be updated in batches. It is not like Updating each record in hibernate ..