Reputation: 559
I am getting strange error Caused by:
java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint
While executing my below code:
Product DAO.java
@Id
@Column(name = "no", columnDefinition = "NUMBER")
private int serial_number;
//No getter and setter for this field
@Column(name = "fname", columnDefinition = "VARCHAR2(50)")
private int fname;
@Column(name = "lname", columnDefinition = "VARCHAR2(50)")
private int lname;
// Getter and setter for fname and lname
ProductService.java
Product po = new Product();
po.setfname = "Tom";
po.setlname = "John";
//I am not setting 'no' field value since I have created sequence in my oracle table to auto increment the value.
When I am running this code, I am getting unique constraint error on field 'no'. Can anyone help me in identifying what I am doing wrong in my code. When I have already created sequence for 'no' field in my table, do I need to make any change in config file or code? Since its the production database, I do not know the sequence name also.
hibernate-cgf.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.password">pass</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="dao.Product"></mapping>
</session-factory>
</hibernate-configuration>
Upvotes: 0
Views: 1844
Reputation: 36
Your id field serial_number
is an int which is initialized to zero, and your mapping for @Id does not include a @GeneratedValue annotation, so hibernate will assume you are assigning the id manually and save it as zero every time you persist an object, causing the SQLIntegrityConstraintViolationException
. You need to add a @GeneratedValue annotation and you can also choose a strategy, like this:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "no", columnDefinition = "NUMBER")
private int serial_number;
Upvotes: 2