Problem description:
In hibernate technology, each table in the database corresponds to a ing file, which describes the type, length, whether it is empty, and other attributes of each field in the database table. In an ongoing table
During the insert (update) Operation of the record, Hibernate automatically generates an insert (update) SQL statement containing all fields according to the description in the ing file. If the value of a field in the ing file is
If it is null and the default value defined in the database table is not null, Hibernate inserts the null value into the table without using the default value of this field.
Solution:
Add dynamic-insert = "true" and dynamic-update = "true" to the description of the database table in the hibernate ing file"
When hibernate performs the insert (update) operation, it only assigns values to fields whose values are not empty, fields with null values use the default values defined in the database table.
Example:
Table person:
Create Table person (
I _id int (11) not null auto_increment,
C_name varchar (100) not null default 'zhang san ',
Primary Key (ID)
)
Person. HBM. xml:
<Hibernate-mapping package = "cn.com. lough. Model">
<Class
Name = "person"
Table = "person"
Lazy = "false"
>
<Meta attribute = "sync-Dao"> true </meta>
<Cache Usage = "read-write"/>
<ID
Name = "IID"
Type = "integer"
Column = "I _id"
>
<Generator class = "native"/>
</ID>
<Property
Name = "cname"
Column = "c_name"
Type = "string"
Not-null = "false"
Length = "128"
/>
</Hibernate-mapping>
Run the program
Person P = new person ();
Hifacloud. Save (P );
The SQL statement generated by Hibernate is insert into person (c_name) values (null );
The database table result is
I _id c_name
1 null
Modify person. HBM. XML:
<Hibernate-mapping package = "cn.com. lough. Model">
<Class
Name = "person"
Table = "person"
Lazy = "false"
Dynamic-insert = "true"
>
<Meta attribute = "sync-Dao"> true </meta>
<Cache Usage = "read-write"/>
<ID
Name = "IID"
Type = "integer"
Column = "I _id"
>
<Generator class = "native"/>
</ID>
<Property
Name = "cname"
Column = "c_name"
Type = "string"
Not-null = "false"
Length = "128"
/>
</Hibernate-mapping>
Run the program again. The SQL statement generated by Hibernate is insert into person () values ();
The database table result is
I _id c_name
1 null
2 Zhang San