-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: Cascade saving Parent Child tables - ConstraintViolation
PostPosted: Tue May 31, 2011 2:03 am 
Newbie

Joined: Tue May 31, 2011 1:47 am
Posts: 2
Code snippets for the tables, hibernate mapping and Main class are given below.

Basically I am trying to use cascade feature to save the Parent and child records. I am getting the following exception. Please let me know where I am going wrong.

Code:
Hibernate: select max(ID) from T_PARENT
Hibernate: select tparentchi_.PARENT_ID, tparentchi_.ORDER_ID, tparentchi_.CHILD_ID from T_PARENT_CHILD tparentchi_ where tparentchi_.PARENT_ID=? and tparentchi_.ORDER_ID=? and tparentchi_.CHILD_ID=?
Hibernate: select max(ID) from T_CHILD
Hibernate: select tparentchi_.PARENT_ID, tparentchi_.ORDER_ID, tparentchi_.CHILD_ID from T_PARENT_CHILD tparentchi_ where tparentchi_.PARENT_ID=? and tparentchi_.ORDER_ID=? and tparentchi_.CHILD_ID=?
Hibernate: insert into T_PARENT (NAME, ID) values (?, ?)
Hibernate: insert into T_CHILD (NAME, ID) values (?, ?)
Hibernate: insert into T_PARENT_CHILD (PARENT_ID, ORDER_ID, CHILD_ID) values (?, ?, ?)
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
   at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
   at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
   at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
   at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:114)
   at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:109)
   at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:244)
   at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2393)
   at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2856)
   at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79)
   at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
   at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
   at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
   at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
   at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
   at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
   at Main.main(Main.java:34)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
   at java.lang.reflect.Method.invoke(Method.java:597)
   at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)
Caused by: java.sql.BatchUpdateException: Column 'PARENT_ID' cannot be null
   at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2007)
   at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1443)
   at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
   at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
   ... 18 more



Table Details
Code:
CREATE TABLE `T_PARENT`
(
   `ID` INT NOT NULL AUTO_INCREMENT,
   `NAME` VARCHAR(32),
   PRIMARY KEY (`ID`)
) TYPE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `T_CHILD`
(
   `ID` INT NOT NULL AUTO_INCREMENT,
   `NAME` VARCHAR(32),
   PRIMARY KEY (`ID`)
) TYPE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `T_PARENT_CHILD`
(
   `PARENT_ID` INT NOT NULL,
   `CHILD_ID` INT NOT NULL,
   `ORDER_ID` INT NOT NULL,
   PRIMARY KEY (`PARENT_ID`, `CHILD_ID`, `ORDER_ID`),
   INDEX `PARENT_ID` (`PARENT_ID` ASC),
   INDEX `CHILD_ID` (`CHILD_ID` ASC)
) TYPE=MyISAM DEFAULT CHARSET=utf8;


ALTER TABLE `T_PARENT_CHILD` ADD CONSTRAINT `FK_TPC_PARENT`
   FOREIGN KEY (`PARENT_ID`) REFERENCES `T_PARENT` (`ID`);

ALTER TABLE `T_PARENT_CHILD` ADD CONSTRAINT `FK_TPC_CHILD`
   FOREIGN KEY (`CHILD_ID`) REFERENCES `T_CHILD` (`ID`);



Hibernate Mapping

Code:
  <class name="hibtest.model.TParent" table="T_PARENT">
    <id name="id" type="java.lang.Integer">
      <column name="ID" precision="5" scale="0"/>
      <generator class="increment"/>
    </id>
    <property name="name" type="string">
      <column name="NAME" length="20" not-null="true"/>
    </property>
    <set name="children" cascade="all" inverse="true">
      <key><column name="PARENT_ID" not-null="true"/></key>
      <one-to-many class="hibtest.model.TParentChild"></one-to-many>
    </set>
  </class>

  <class name="hibtest.model.TChild" table="T_CHILD">
    <id name="id" type="java.lang.Integer">
      <column name="ID" precision="5" scale="0"/>
      <generator class="increment"/>
    </id>
    <property name="name" type="string">
      <column name="NAME" length="20" not-null="true"/>
    </property>
    <set name="parent" table="T_PARENT_CHILD">
      <key><column name="CHILD_ID" not-null="true"/></key>
      <one-to-many class="hibtest.model.TParentChild"></one-to-many>
    </set>
  </class>

  <class name="hibtest.model.TParentChild" table="T_PARENT_CHILD">
    <composite-id name="id" class="hibtest.model.TParentChildId">
      <key-property name="parentId" column="PARENT_ID" type="java.lang.Integer" />
      <key-property name="orderId" column="ORDER_ID" type="java.lang.Integer" />
      <key-property name="childId" column="CHILD_ID" type="java.lang.Integer" />
    </composite-id>
    <many-to-one name="parent" insert="false" update="false"
                 column="PARENT_ID" class="hibtest.model.TParent"/>
    <many-to-one name="child" lazy="false" insert="false" update="false"
                 cascade="all" column="CHILD_ID" class="hibtest.model.TChild"/>
  </class>



Main class

Code:
import hibtest.model.TChild;
import hibtest.model.TParent;
import hibtest.model.TParentChild;
import hibtest.model.TParentChildId;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.util.HashSet;
import java.util.Set;

public class Main {
    private static final SessionFactory ourSessionFactory;

    static {
        try {
            ourSessionFactory = new Configuration().
                    configure("hibernate.cfg.xml").
                    buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
        return ourSessionFactory.openSession();
    }

    public static void main(final String[] args) throws Exception {
        final Session session = getSession();
        try {
            session.saveOrUpdate(getParent());
            session.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    private static TParent getParent () {
        TParent parent = new TParent ();
        parent.setName("pname");
        Set<TParentChild> children = new HashSet<TParentChild>();
        children.add(getParentChild(parent, "c1", 1));
        children.add(getParentChild(parent, "c2", 2));
        parent.setChildren(children);
        return parent;
    }

    private static TChild getChild (String name) {
        TChild child = new TChild();
        child.setName(name);
        return child;
    }

    private static TParentChild getParentChild (TParent parent, String childName, Integer order) {
        TParentChild pc = new TParentChild();
        TParentChildId pcId = new TParentChildId();
        pcId.setParentId(parent.getId());
        pcId.setOrderId(order);
        pc.setId(pcId);
        TChild child = getChild(childName);
        Set<TParentChild> parentSet = new HashSet<TParentChild>();
        parentSet.add(pc);
        child.setParent(parentSet);
        pc.setChild(child);
        pc.setParent(parent);
        return pc;
    }
}



Top
 Profile  
 
 Post subject: Re: Cascade saving Parent Child tables - ConstraintViolation
PostPosted: Tue May 31, 2011 4:11 am 
Newbie

Joined: Tue May 31, 2011 1:47 am
Posts: 2
Found the answer, change required in Hibernate Mapping

Code:
  <class name="hibtest.model.TParentChild" table="T_PARENT_CHILD">
    <composite-id name="id" class="hibtest.model.TParentChildId">
      <key-many-to-one name="parent" column="PARENT_ID" class="hibtest.model.TParent"/>
      <key-property name="orderId" column="ORDER_ID" type="java.lang.Integer" />
    </composite-id>
    <many-to-one name="child" lazy="false" fetch="select"
                 cascade="all" column="CHILD_ID" class="hibtest.model.TChild"/>
  </class>


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.