Next val for the sequence not generated for Hibernate batch inserts

Viewed 259

I have the following table named CONTACT in oracle database:

ID NOT NULL NUMBER(19) PRIMARY KEY,
CITY VARCHAR2(56),
EMAIL VARCHAR2(120),
FIRSTNAME VARCHAR2(40),
LASTNAME VARCHAR2(40)

The sequence name is CONTACT_ID_SEQ

Following is the mapping class:

@Entity
@Table(name ="CONTACT")
public class Contact implements Serializable{
  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CONTACT_ID_SEQ")
  @SequenceGenerator(name = "CONTACT_ID_SEQ", sequenceName = "CONTACT_ID_SEQ")  
  private Long id;
 
  //All the other column mappings
  //Constructors
  //Getter setters

}

I am doing a batch inserts. Basically inserting a list of contacts. List size is at least 100. Following is the hibernate configuration:

<property name="show_sql">true</property>
<property name="hibernate.jdbc.batch_size">20</property>
<property name="hibernate.cache.use_second_level_cache">false</property>

So the batch size is 20.

Following is the code for insert:

public void saveData(List<Contact> contacts){
  Session session = HibernateFactory.openSession();
  Transaction transaction = null;
  try{
        int i = 0;
        transaction = session.getTransaction() == null ? session.beginTransaction() : 
        session.getTransaction(); 
        for(Contact c : contacts){
            session.save(c);
            if(i > 0 && i % 20 == 0){
              log.info("Finished batch ");
              session.flush();
              session.clear();
            }
            i++;
        }
        transaction.commit();

  }catch(HibernateException e){
        transaction.rollback();
  }finally{
       session.close();
  }
}

I am getting the exception:

Error Uploading to Database: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute batch
.
.
.
.
Caused by: java.sql.BatchUpdateException: ORA-00001: unique constraint (CONTACT_DB.SYS_C0013605) violated

I am seeing the next val for the sequence being generated only once:

Hibernate: select CONTACT_ID_SEQ.nextval from dual

After the first batch(size 20) of inserts is complete. I presume it should generate the next val for the sequence once again.

I have been trying to address the constraint violation exception without any success. Any help would be appreciated. Thanks in advance!

0 Answers
Related