If session. Update (Object O) is directly used in hibernate, all fields in this table will be updated.
If you do not assign values to fields other than the fields to be updated, these fields are left blank.
Public class teachertest
{
@ Test
Public void Update ()
{
Session session = hibernateuitl. getsessionfactory (). getcurrentsession ();
Session. begintransaction ();
Teacher t = (teacher) Session. Get (teacher. class, 3 );
T. setname ("yangtb2 ");
Session. Update (t );
Session. gettransaction (). Commit ();
}
}
The SQL statement executed by hibernate:
Hibernate:
Update
Teacher
Set
Age = ?,
Birthday = ?,
Name = ?,
Title =?
Where
Id =?
We only changed the name attribute, while the hibernate SQL statement changed all fields once.
In this way, if we have fields of the text type and the content of this type is stored in thousands or tens of thousands of characters, the efficiency will be very low.
So how can we only change the updated field? There are three methods:
1. Set the property tag update = "false" in XML, as shown in the following figure: do not change the property of age.
<Property name = "Age" update = "false"> </property>
<Property name = "Age" update = "false"> </property>
Add @ column (updatable = false) to the get method of the attribute in annotation)
@ Column (updatable = false)
Public int getage (){
Return age;
}
When executing the update method, we will find that the age attribute will not be changed.
Hibernate:
Update
Teacher
Set
Birthday = ?,
Name = ?,
Title =?
Where
Id =?
Disadvantage: inflexible
2. Use Dynamic-update = "true" in XML"
<Class name = "com. sccin. entity. Student" table = "student" dynamic-update = "true">
<Class name = "com. sccin. entity. Student" table = "student" dynamic-update = "true">
OK, so you do not need to set the field.
However, this method does not exist in annotation.
3. Method 3: Use hql statements (flexible and convenient)
Modify data using hql statements
Public void Update ()
{
Session session = hibernateuitl. getsessionfactory (). getcurrentsession ();
Session. begintransaction ();
Query query = session. createquery ("update teacher t set T. Name = 'hangzhou', T. Age = '20' where id = 3 ");
Query.exe cuteupdate ();
Session. gettransaction (). Commit ();
}
Note: update each field with a comma. Otherwise, an error is returned.
The SQL statement executed by hibernate:
Hibernate:
Update
Teacher
Set
Name = 'hangzhou', age = '20'
Where
Id = 3
In this way, only the updated fields are updated.
Some methods are as follows:
1. Use the hidden tag to find out unnecessary fields and then return them.
2. Check the database and declare a new object. Then, set the data transmitted from the page to save the newly declared object.
Original post address: http://www.cnblogs.com/hyteddy/archive/2011/07/21/2113175.html