Hibernate self-increment column save failed issue

Source: Internet
Author: User

Author:hiu

Correction: Today (2014-07-07) only discovered the problem, I put @id in the entity class ID, @Id is the primary key, should be set in the entity class Keyjobno, the previous article may mislead everyone, now correct, see the following red corrections.


Recently changed from Ibatis to Hibernate, during a series of problems encountered, and today, because of the problem caused by the increase in the issue of saving the Times, now recorded, so that later to forget the view

This problem is actually caused by the annotated error of the self-increment column when using MyEclipse to generate the entity class for the table.

Cause: The entity class self-increment annotation generated using the MyEclipse hibernate Reverse engineening is set on the primary key keyjobno instead of the corresponding ID column

Workaround: set the self-increment annotation to the corresponding self-increment column ID


Database Employee table:


Here is the main list of some of the fields, the key is that the ID and Keyjobno,id set is the self-increment column, Keyjobno set as the primary key


Generating entity classes using MyEclipse's hibernate Reverse engineening



Generated entity class employee, just put out the keyjobno,id, the others are not posted

@Entity @table (name = "Employee", Catalog = "Union_ssh", uniqueconstraints = @UniqueConstraint (ColumnNames = "id")) public Class Employee implements Java.io.Serializable {//fieldsprivate String keyjobno;private Integer id; @Id @generatedvalue ( Strategy = IDENTITY) @Column (name = "Keyjobno", unique = true, Nullable = false, length =) public String getkeyjobno () {R Eturn This.keyjobno;} public void Setkeyjobno (String keyjobno) {this.keyjobno = Keyjobno;} @Column (name = "id", unique = true, Nullable = false) public Integer GetId () {return this.id;} public void SetId (Integer id) {this.id = id;}}

Service Layer

Public employee Save (employee employee) throws SQLException {      employee.setkeyjobno ("K8888");      Employeedao.save (employee);      return employee;}

DAO layer

@Overridepublic Serializable Save (T o) {     return this.getcurrentsession (). Save (O);

SQL statement printed by the console:

2014-07-04 14:10:50 [org.hibernate.sql]-[debug] insert INTO Union_ssh.employee (Born_boon, Borndate, Company, CreateDate, dept, Getborn_date, getmarry_date, id, Identitycard, ifout, interest, jobno, lodging, Marry, Marry_b  Oon, name, Nativename, operator, phone, politicsface, sex) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?, ?, ?, ?, ?, ?) Hibernate:insert to Union_ssh.employee (Born_boon, Borndate, Company, CreateDate, dept, Getborn_d Ate, getmarry_date, ID, Identitycard, ifout, interest, jobno, lodging, Marry, Marry_boon, name, Nativename, operator, Phon E, politicsface, Sex) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) 2014-07-04 14:10:50 [org.hibernate.engine.jdbc.spi.sqlexceptionhelper]-[debug] Field ' keyjobno ' doesn ' t have a default Value [N/a]<span style= "color: #ff0000;" ><strong>java.sql.sqlexception:field ' keyjobno ' doesn ' t have a default VALUE&LT;/STRONG&GT;&LT;/SPAn> 

Notice the red part, the error said I keyjobno no default value, the strangest is here, I clearly in the service layer set up
Employee.setkeyjobno ("K8888");

Obviously already set the value for Keyjobno, unexpectedly also said I did not have the default value. Look at the SQL statement, there is an ID, but there is no keyjobno, supposedly ID in the database table set the self-increment, here should not be inserted, but Keyjobno is already set the value, but not shown in the inserted SQL, This is due to the annotations when the keyjobno is set in order to self-increment the column.


Now take a look at the annotations in the entity class:

@Id @generatedvalue (strategy = IDENTITY) @Column (name = "Keyjobno", unique = true, Nullable = false, length =) public Stri Ng Getkeyjobno () {   return this.keyjobno;}


Remark Meaning:

@Id-the annotation declares the identity attribute of the entity bean (the primary key in the corresponding table).

@GeneratedValue-the annotation declares the generation strategy of the primary key. The annotation has the following properties, such as

strategy Specifies the generated policy (JPA-defined), which is a generationtype. The default is GenerationType. auto   
    Generationtype.auto primary key controlled by program  

Generationtype.identity primary key is generated by the database itself (mainly by its own active growth type)


See note explanation, we should be clear, I set in the database table is the ID self-increment column, but the generated entity class self-increment column is Keyjobno, this is the reason why the save failed, the entity class to the following form, mainly to the keyjobno of the self-increment annotations cut to the ID column

@Entity @table (name = "Employee", Catalog = "Union_ssh", uniqueconstraints = @UniqueConstraint (ColumnNames = "id")) public Class Employee implements Java.io.Serializable {private String keyjobno;private Integer ID; @Column (name = "Keyjobno", Uni Que = true, nullable = false, length = () public String getkeyjobno () {return this.keyjobno;} public void Setkeyjobno (String keyjobno) {this.keyjobno = Keyjobno;}  @Id @generatedvalue (strategy = IDENTITY) @Column (name = "Id", unique = true, Nullable = false) public Integer GetId () {return This.id;} public void SetId (Integer id) {this.id = id;}}


@Id set in the Id property of the Get method, remove the @id here, because @id is the primary key, can see the above Database Employee table diagram, Keyjobno is the primary key, so should @id set in the Keyjobno get method on the

@Id @column (name = "Keyjobno", unique = true, Nullable = false, length =) public String getkeyjobno () {return this.keyjob No;}

Assuming you do not correct this, it is not a problem to do a separate insert operation on the employee table, assuming you have other tables associated with the Keyjobno primary key of the employee table, but you did not set @id on Keyjobno, then here's the problem. If you insert data into the associated table, you cannot insert it, because the associated table cannot be inserted because it does not correspond to the primary key of the employee. Today, I used the In_union_his table to associate the employee table, while doing in_union_his table insert operation, constantly prompted foreign key constraints failed to insert data into the child table In_union_his
, here is the error message that I failed today: Cannot add or update a child row:a FOREIGN KEY constraint fails

2014-07-07 10:03:18 [org.hibernate.sql]-[debug] insert INTO Union_ssh.employee (Bornboon, Borndate, Company, CreateDate, dept, Getborndate, Getmarrydate, Identitycard, ifout, interest, jobno, keyjobno, lodging, Marry, Marr Yboon, name, Nativename, operator, phone, politicsface, sex) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?, ?, ?, ?, ?, ?, ?) Hibernate:insert to Union_ssh.employee (Bornboon, Borndate, Company, CreateDate, dept, Getborndat E, Getmarrydate, Identitycard, ifout, interest, jobno, keyjobno, lodging, Marry, Marryboon, name, nativename, operator, ph One, politicsface, sex) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) 2014-07-07 10:03:18 [Org.hibernate.id.identifiergeneratorhelper]-[debug] natively generated identity:6602014-07-07 10:03:18 [Org.hibernate.engine.spi.actionqueue]-[debug] executing identity-insert immediately2014-07-07 10:03:18 [ Org.hibernate.sql]-[debug] InseRT into Union_ssh.in_union_his (CreateDate, Keyjobno, inuniondate, operator) VALUES (?,?,?, ?) Hibernate:insert into Union_ssh.in_union_his (CreateDate, Keyjobno, inuniondate, operator) Valu ES (?,?,?,?) 2014-07-07 10:03:18 [org.hibernate.engine.jdbc.spi.sqlexceptionhelper]-[debug]cannot Add or update a child row:a FOREIGN KEY constraint fails (' Union_ssh '. ' In_union_his ', constraint ' fk_in_union_his ' foreign key (' Keyjobno ') REFERENCES ' Employee ' (' Keyjobno ') on the DELETE CASCADE on UPDATE CASCADE) [n/A] Com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:Cannot Add or update a child row:a foreign Key constraint fails (' Union_ssh '. ' In_union_his ', constraint ' fk_in_union_his ' FOREIGN KEY (' keyjobno ') REFERENCES ' Employee ' (' Keyjobno ') on the DELETE CASCADE on UPDATE CASCADE) at Sun.reflect.NativeConstructorAccessorImpl.newInstance0 ( Native Method)
just to set @id in the database table primary key corresponding entity class properties Keyjobno, the key is that I previously set the @id on the id attribute.


Deploy again, run the Save, and the console prints out the SQL statement:

2014-07-04 14:30:21 [Org.hibernate.sql]-[debug] insert INTO Union_ssh.employee (Born_boon, Borndate, Company, C  Reatedate, Dept, Getborn_date, Getmarry_date, Identitycard, ifout, interest, jobno, keyjobno, lodging, Marry, Marry_boon, Name, Nativename, operator, phone, politicsface, sex) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?, ?, ?, ?, ?) Hibernate:insert to Union_ssh.employee (Born_boon, Borndate, Company, CreateDate, dept, Getborn_d Ate, Getmarry_date, Identitycard, ifout, interest, jobno, keyjobno, lodging, Marry, Marry_boon, name, Nativename, operator , phone, politicsface, sex) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) 2014-07-04 14:30:21 [Org.hibernate.id.identifiergeneratorhelper]-[debug] natively generated identity:557 
Last line natively generated identity:557 this sentence is what meaning, in fact, 557 is the ID of the inserted record, because I have 556 records in the database, which means that the preservation of success, we can see, This SQL statement has no ID saved, that is, the SQL statement inserted when the ID is not inserted, but in the database itself actively added? today (2014-07-07) again tested, found that the display does not show that the Id can be inserted successfully, is not displayed because I @id the note before,@GeneratedValue (strategy = IDENTITY) Set in the ID Lie didn't show up and I'm expected to be just for you annotation set in the self-increment column and the self-increment column is the primary key, the SQL statement does not display this column when inserting

Summary: The error in the annotation place is due to local errors caused by the use of MyEclipse to generate entity classes, so do not rely too much on your own initiative to generate entity classes. Personal Push the reason, is because I set the ID is self-increment, but the Keyjobno column is set as the primary key, that is to say, these two columns are unique, myeclipse in the generated entity class is possible can not distinguish, the self-added annotation set in the column of the primary key, no detailed study, we are interested, Able to study under.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.