title: Batch entry 0 insert into debit (amount, cid, description, did) values ('100', 0, 'rajesh', 5) was aborted: ERROR: insert or update on table "debit"
body: <p>I have two tables <code>Credit</code> and <code>Debit</code>. <code>Credit</code> is Parent table and <code>Debit</code> is child table. I can provide a one-to-many relationship with two table. In <code>Credit</code> table single row of data and in Debit table Multiple row of data.</p>
  
  <p>I has try try to insert data then this type of error is occurs. </p>
  
  <blockquote>
    <p>ERROR: org.hibernate.util.JDBCExceptionReporter - Batch entry 0 insert into debit (amount, cid, description, did) values ('100', 0, 'rajesh', 5) was aborted: ERROR: insert or update on table "debit" violates foreign key constraint "fk5b094ec5422fc54"
      Detail: Key (cid)=(0) is not present in table "credit".  Call getNextException to see other errors in the batch.
    WARN : org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 23503
    ERROR: org.hibernate.util.JDBCExceptionReporter - ERROR: insert or update on table "debit" violates foreign key constraint "fk5b094ec5422fc54"
      Detail: Key (cid)=(0) is not present in table "credit".
    ERROR: org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
    org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update</p>
  </blockquote>
  
  <p><strong>1.Credit.java - Entity</strong></p>
  
  <pre><code>package com.rojmat.entity;
  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.Date;
  import java.util.List;
  import javax.persistence.CascadeType;
  import javax.persistence.Column;
  import javax.persistence.Entity;
  import javax.persistence.GeneratedValue;
  import javax.persistence.GenerationType;
  import javax.persistence.Id;
  import javax.persistence.JoinColumn;
  import javax.persistence.JoinColumns;
  import javax.persistence.JoinTable;
  import javax.persistence.OneToMany;
  import javax.persistence.Table;
  import org.springframework.core.annotation.Order;
  
  @Entity
  @Table(name="credit")
  public class Credit extends BaseEntity{
      @Id
      @GeneratedValue(strategy=GenerationType.AUTO)
      @Column
      private long cid;
      @Column @Order
      private long openingbalance;
      @Column
      private Date date;
      @Column @Order
      private long debittotal;
      @Column @Order
      private long drawertotal;
      @Column @Order
      private long debittotalplusdrawertotal;
      @Column @Order
      private long todaybusiness;
  
      @OneToMany(cascade={CascadeType.ALL})
      /*@JoinTable(name="credit_debit", 
                 joinColumns=@JoinColumn(name="c_id"), 
                 inverseJoinColumns=@JoinColumn(name="d_id"))*/
       @JoinColumns({@JoinColumn(name = "cid" ,referencedColumnName = "cid")})
      private List&lt;Debit&gt; debits = new ArrayList&lt;Debit&gt;(Arrays.asList());
      public Credit() {
  
      }
      public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
              long debittotalplusdrawertotal, long todaybusiness, List&lt;Debit&gt; debits) {
          super();
          this.cid = cid;
          this.openingbalance = openingbalance;
          this.date = date;
          this.debittotal = debittotal;
          this.drawertotal = drawertotal;
          this.debittotalplusdrawertotal = debittotalplusdrawertotal;
          this.todaybusiness = todaybusiness;
          this.debits = debits;
      }
      public long getCid() {
          return cid;
      }
      public void setCid(long cid) {
          this.cid = cid;
      }
      public long getOpeningbalance() {
          return openingbalance;
      }
      public void setOpeningbalance(long openingbalance) {
          this.openingbalance = openingbalance;
      }   
      public Date getDate() {
          return date;
      }
      public void setDate(Date date) {
          this.date = date;
      }
      public long getDebittotal() {
          return debittotal;
      }
      public void setDebittotal(long debittotal) {
          this.debittotal = debittotal;
      }
      public long getDrawertotal() {
          return drawertotal;
      }
      public void setDrawertotal(long drawertotal) {
          this.drawertotal = drawertotal;
      }
      public long getDebittotalplusdrawertotal() {
          return debittotalplusdrawertotal;
      }
      public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
          this.debittotalplusdrawertotal = debittotalplusdrawertotal;
      }
      public long getTodaybusiness() {
          return todaybusiness;
      }
      public void setTodaybusiness(long todaybusiness) {
          this.todaybusiness = todaybusiness;
      }
      public List&lt;Debit&gt; getDebit() { 
          return debits;
      }   
      public void setDebit(List&lt;Debit&gt; debit) {   
          this.debits = debits;
      }
      @Override
      public String toString() {
              return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
      }
  }
  
  </code></pre>
  
  <p><strong>2.Debit.java - Entity</strong></p>
  
  <pre><code>package com.rojmat.entity;
  import javax.persistence.Column;
  import javax.persistence.Entity;
  import javax.persistence.GeneratedValue;
  import javax.persistence.GenerationType;
  import javax.persistence.Id;
  import javax.persistence.Table;
  
  @Entity
  @Table(name="debit")
  public class Debit {
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      @Column
      private long did;
      @Column(name="cid")
      private long cid;
      @Column
      private String amount;
      @Column
      private String description; 
  
      public long getDid() {
          return did;
      }
      public void setDid(long did) {
          this.did = did;
      }
      public Debit() {
  
      }
      public Debit(String amount, String description) {
          super();
          this.amount = amount;
          this.description = description;
      }
      public String getAmount() {
          return amount;
      }
      public void setAmount(String amount) {
          this.amount = amount;
      }
      public String getDescription() {
          return description;
      }
      public void setDescription(String description) {
          this.description = description;
      }
      @Override
      public String toString() {
              return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
      }
  }
  
  </code></pre>
  
  <p>3.CreditController.java</p>
  
  <pre><code>@RequestMapping(value="/useraccount", method=RequestMethod.POST)
      public String userAccount(@RequestParam(value = "amount") String[] amount, 
                                @RequestParam(value = "description") String[] description, 
                                ModelMap model, HttpServletRequest request, HttpSession session,@ModelAttribute("command")Credit credit, BindingResult result)
      {
          try {
              List&lt;Debit&gt; debits = new ArrayList&lt;Debit&gt;(Arrays.asList());
              debits = credit.getDebit();
              for(int i=0; i&lt;amount.length; i++) {
                  Debit debit = new Debit();
                  debit.setAmount(amount[i]);
                  debit.setDescription(description[i]);
                  debits.add(debit);
              }   
              System.out.println("debits ="+debits);
              List&lt;Debit&gt; debits1 = new ArrayList&lt;Debit&gt;();
              credit.setDebit(debits1);
              for(int i=0; i&lt;debits.size(); i++)
              {
                  debits1.add(new Debit(debits.get(i).getAmount(),debits.get(i).getDescription()));
              }
              System.out.println("debits1 ="+debits1);
              User user = new User();
               // Credit Data Set
                  credit.setOpeningbalance(credit.getOpeningbalance());
                  credit.setDate(credit.getDate());
                  credit.setDebittotal(credit.getDebittotal());
                  credit.setDrawertotal(credit.getDrawertotal());
                  credit.setDebittotalplusdrawertotal(credit.getDebittotalplusdrawertotal());
                  credit.setTodaybusiness(credit.getTodaybusiness());
                  credit.setCreatedBy(user.getEmail());
                  credit.setCreatedDate(new Date());
                  credit.setUpdatedBy(user.getEmail());
                  credit.setUpdatedDate(new Date());  
              //  Debit Data set  
                  System.out.println("Debit List = " + debits1.size());
                  System.out.println("Credit and Debit data seved successfully");
                  creditService.addCreditDebit(credit);
                  model.put("success", "Data Saved Successfully");
          }catch(Exception e) {
              e.printStackTrace();
          }
          return "redirect:useraccount";
      }
  </code></pre>
  
  <p>4.CreditDaoImpl.java</p>
  
  <pre><code>package com.rojmat.daoImpl;
  import java.util.List;
  import org.hibernate.SessionFactory;
  import org.hibernate.transform.Transformers;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Repository;
  import com.rojmat.dao.CreditDao;
  import com.rojmat.entity.Credit;
  
  @Repository
  public class CreditDaoImpl implements CreditDao{
  
      @Autowired
      private SessionFactory sessionFactory;
      @Override
      public void addCreditDebit(Credit credit) {
          try {
              sessionFactory.getCurrentSession().saveOrUpdate(credit);
          } catch(Exception e) {
              e.printStackTrace();
          }
      }
  </code></pre>
  
  <blockquote>
    <p>"debits =[Debit [did=0, amount =100, description=rajesh], Debit [did=0, amount =200, description=market], Debit [did=0, amount =300, description=nasto karyo]]
    debits1 =[Debit [did=0, amount =100, description=rajesh], Debit [did=0, amount =200, description=market], Debit [did=0, amount =300, description=nasto karyo]]
    Debit List = 3
    Credit and Debit data seved successfully
    Hibernate: select nextval ('hibernate_sequence')
    Hibernate: select nextval ('hibernate_sequence')
    Hibernate: select nextval ('hibernate_sequence')
    Hibernate: select nextval ('hibernate_sequence')
    Hibernate: insert into credit (createdby, createddate, updatedby, updateddate, date, debittotal, debittotalplusdrawertotal, drawertotal, openingbalance, todaybusiness, cid) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    Hibernate: insert into debit (amount, cid, description, did) values (?, ?, ?, ?)
    Hibernate: insert into debit (amount, cid, description, did) values (?, ?, ?, ?)
    Hibernate: insert into debit (amount, cid, description, did) values (?, ?, ?, ?)
    WARN : org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 23503
    ERROR: org.hibernate.util.JDBCExceptionReporter - Batch entry 0 insert into debit (amount, cid, description, did) values ('100', 0, 'rajesh', 5) was aborted: ERROR: insert or update on table "debit" violates foreign key constraint "fk5b094ec5422fc54"
      Detail: Key (cid)=(0) is not present in table "credit".  Call getNextException to see other errors in the batch.
    WARN : org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 23503
    ERROR: org.hibernate.util.JDBCExceptionReporter - ERROR: insert or update on table "debit" violates foreign key constraint "fk5b094ec5422fc54"
      Detail: Key (cid)=(0) is not present in table "credit".
    ERROR: org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
    org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
        at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
        at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
        at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
        at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
        at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
        at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
        at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
        at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:663)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:765)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:734)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:518)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
        at com.sun.proxy.$Proxy43.addCreditDebit(Unknown Source)
        at com.rojmat.controller.UserController.userAccount(UserController.java:110)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:849)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:760)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:748)
    Caused by: java.sql.BatchUpdateException: Batch entry 0 insert into debit (amount, cid, description, did) values ('100', 0, 'rajesh', 5) was aborted: ERROR: insert or update on table "debit" violates foreign key constraint "fk5b094ec5422fc54"
      Detail: Key (cid)=(0) is not present in table "credit".  Call getNextException to see other errors in the batch.
        at org.postgresql.jdbc.BatchResultHandler.handleError(BatchResultHandler.java:148)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2184)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:481)
        at org.postgresql.jdbc.PgStatement.executeBatch(PgStatement.java:840)
        at org.postgresql.jdbc.PgPreparedStatement.executeBatch(PgPreparedStatement.java:1538)
        at org.apache.commons.dbcp.DelegatingPreparedStatement.executeBatch(DelegatingPreparedStatement.java:231)
        at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
        ... 56 more
    Caused by: org.postgresql.util.PSQLException: ERROR: insert or update on table "debit" violates foreign key constraint "fk5b094ec5422fc54"
      Detail: Key (cid)=(0) is not present in table "credit".
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
        ... 62 more"</p>
  </blockquote>