Everything starts from data insertion. If there is no data insertion, there will be no data to update, delete, and modify. The most frequently used method for data insertion in Hibernate is the SAVE () method. Annotations to the Save method in hibernate's official API are simple: persists the specified temporary object, and first specifies an identifier, that is, the oId we call, except when the oId generation policy is assigned.
Although the comment is simple, it discloses enough information to us. We analyze it from input, operation, and output.
1. Input: a temporary object. This does not mean that we cannot use persistence objects and free objects as parameters, but that such operations are not standard. Just like a man wearing a dress, it's just unreasonable to say that you cannot wear it.
2. operation: first, generate an oId for the temporary object based on the specified OID generation policy. Generally, the oId of the temporary object is null, unless you use the Assign policy or manually specify an oId, but it turns out that it is useless at this moment. Then, place the object in the cache to make it a Persistent Object. Finally, plan an insert statement. Note that it is only a plan and has not been executed, the SQL statement is executed only when the session clears the cache.
3. Output: A Persistent Object and an SQL statement. This statement is not very accurate. This is just for ease of understanding.
As far as I understand it, the SAVE () method is like when a hero in Warcraft is outside the class, it is the same as to pick up the treasures from the monster and put them on the body.
Previously, it was useless to specify an oId manually. You can use the followingCodeFragment for verification:
Customer customer = new customer ();
Customer. setid (3l );
Session. Save (customer );
System. Out. println (customer. GETID ());
The result shows that,ProgramThe output ID is generated based on the identifier generator. Note that when the object is in the persistent state, you cannot modify its OID at will. Otherwise, the session will throw an exception when clearing the cache, for example:
Customer customer = new customer ();
Session. Save (customer );
Customer. setid (3l );
TX. Commit ();
The program throws the following exception: org. hibernate. hibernateexception: identifier of an instance of cn.edu. HUST. cm. mypack. Customer was altered from 7 to 3.
I also did the following experiment. The code snippet is as follows:
Customer customer = new customer ();
Session. Save (customer );
Session. Save (customer );
TX. Commit ();
The customer is in the temporary state when the SAVE () method is called for the first time, and the Save () method is called for the second time, it is already in the persistent state. It turns out that the second save operation is completely redundant, hibernate did not plan an insert statement for it.