0

I'm new to Hibernate. I'm trying to insert records into my MySQL DB. The first record was inserted properly when I run the Java application, and when I change the details in the code and try to run it again. It throws me error of Duplicate key or integrity constraint. My XML is

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.college.Student" table="STUDENT">
<id column="ID" name="id" type="long" />
<property column="STUDENT_NAME" name="name" type="string" />
<property column="DEGREE" name="degree" type="string" />
<property column="ROLL" name="roll" type="string" />
<property column="PHONE" name="phone" type="string" />
</class>
</hibernate-mapping>

I guess I need to change in this configuration file or Hibernate.cfg.xml because its a primary key . Please suggest me.

Following is the error

WARN: SQL Error: 1062, SQLState: 23000
Feb 18, 2016 11:49:36 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Duplicate key or integrity constraint violation message from server:  "Duplicate entry '0' for key 'PRIMARY'"
Feb 18, 2016 11:49:36 AM  org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Feb 18, 2016 11:49:36 AM org.hibernate.internal.SessionImpl$5 mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [could not execute statement]
Exception in thread "main"  org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:112)
Syed
  • 2,471
  • 10
  • 49
  • 89

3 Answers3

0

Seems like you haven't incremented your primary key column, you will have to do something like this

<id column="ID" name="id" type="long" >
     <generator class="increment" />
</id>
Vihar
  • 3,626
  • 2
  • 24
  • 47
0

You need to give generator for primary key of your table which will auto generated.

<id name="id" type="int" column="id">
     <generator class="native"/>
  </id>

Read this

Pramod Gaikwad
  • 185
  • 1
  • 2
  • 16
0

You need to have an auto increment for an id column.

For MySQL the best choice is to use identity generator, because of MySQL supports it natively.

<id column="ID" name="id" type="long">
    <generator class="identity"/>
</id>

Hibernate will create a table with auto_increment column and MySQL will care about auto increment id

create table STUDENT (
    ID bigint not null auto_increment,
    ...
)

Using other generators is not optimal, because of Hibernate will use additional queries and a table (hibernate_sequence) to increment id.

v.ladynev
  • 19,275
  • 8
  • 46
  • 67