During Hibernate initialization, the SQL statements configured as table predefines insert, delete, update, and select (by id) are placed in the session by default, where insert, update, select operations are performed on all fields in the table. if there are many fields in a table, a large number of fields in the inser for the first time are null, or a small number of fields are often updated, set dynamic-insert and dynamic-update to true on the <class> element of the configuration file. the default value is false.
Create table hbtest (id int, val1 varchar2 (100), val2 varchar2 (100 ));
1. When dynamic-insert is not set
<Class name = "com. test. hb. dynamicupdate. Hbtest" table = "HBTEST">
Hbtest tbo = new Hbtest ();
Tbo. setId (new Integer (2 ));
Tbo. setVal1 ("val1 ");
SessionFactory. getCurrentSession (). save (tbo );
If some fields are empty for insert, hibernate will use the full field insert SQL statement, as shown below:
Insert into HBTEST (VAL1, VAL2, ID) values (?, ?,?)
2. Set dynamic-insert to true. Similarly, hibernate dynamically generates SQL statements and fields without values will not appear in the insert statement.
<Class name = "com. test. hb. dynamicupdate. Hbtest" dynamic-insert = "true" table = "HBTEST">
Insert into HBTEST (VAL1, ID) values (?, ?)
3. When dynamic-update Is Not Set
Hbtest tbo = (Hbtest) sessionFactory. getCurrentSession (). load (Hbtest. class, new Integer (1 ));
Tbo. setVal1 ("valXX ");
Tx. commit ();
Only some fields are updated. hibernate still updates all fields:
Update HBTEST set VAL1 = ?, VAL2 =? Where ID =?
4. If the same operation is set to true, the SQL statement only contains the updated field: update HBTEST set VAL1 =? Where ID =?
<Class name = "com. test. hb. dynamicupdate. Hbtest" dynamic-insert = "true" dynamic-update = "true" table = "HBTEST">
5. The dynamic SQLupdate feature of Hibernate is to save a snapshot when the object is loaded from the database to the hibernate session, and compare it with this snapshot during update, only modified values are updated.
In this case, all fields are updated: The field with no value is updated to null.
Hbtest tbo = new Hbtest ();
Tbo. setId (new Integer (1 ));
Tbo. setVal1 ("val1ZZZ ");
SessionFactory. getCurrentSession (). update (tbo );
In this case, we should use the support provided by Hibernate for SQL and use SQL for update operations.