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.  [ 4 posts ] 
Author Message
 Post subject: One-To-Many Parent with Children in Collection
PostPosted: Wed Aug 16, 2006 1:49 pm 
Newbie

Joined: Wed Aug 16, 2006 1:13 pm
Posts: 9
Location: Oklahoma
I'm using Hibernate 3.0 and MySQL. I cannot get a parent with a collection of children (one-to-many) situation to work. The creation of the child fails on foreign key constraint (parentId not available) I have the exact situation at work and we are using Oracle and sequences for the generation of ids. I supsect that my problem is with using "native" for the id-generation. I'm not sure. I am successful with mappings and automatic id generation on single objects using "native". This seems like timing or improper id generation. Please help. Anyhow, the xdoclet mappings are as follows:

public class Parent implements Serializable

/**
* @hibernate.id generator-class="native" type="java.lang.Long"
* column="parentId" not-null="true"
*/
public Long getParentId() {


public class Child implements Serializable

/**
* @hibernate.id generator-class="native" type="java.lang.Long"
* column="parentId" not-null="true"
*/
public Long getChildId() {

/**
* @hibernate.bag lazy="false" inverse="true" cascade="all"
* order-by="childId"
* @hibernate.collection-key column="parentId"
* @hibernate.collection-one-to-many class="org.dlw.model.Child"
*/
public Collection<Child> getChildren() {

_________________
Piratepete
david.whitehurst@wisplinx.com


Top
 Profile  
 
 Post subject:
PostPosted: Wed Aug 16, 2006 5:34 pm 
Newbie

Joined: Wed Aug 16, 2006 1:13 pm
Posts: 9
Location: Oklahoma
The Bag used for the Collection is on the parent class. The original post looks like the method returning the Collection of children is on the Child object. That's incorrect.

The Hibernate mapping seems correct but I hope that someone sees something I'm doing wrong, eg. with the "native" on the ideas, or maybe Hibernate with MySQL is tricky and requires some other tweak that I don't know about.

Thanks,

_________________
Piratepete
david.whitehurst@wisplinx.com


Top
 Profile  
 
 Post subject:
PostPosted: Wed Aug 16, 2006 7:24 pm 
Newbie

Joined: Wed Aug 16, 2006 1:13 pm
Posts: 9
Location: Oklahoma
Here's the real code and the stack trace.

Code:
package org.dlw.model.business.base;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
* Copyright (C) 2006  David L. Whitehurst<br>
* <p/>
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
* <p/>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.<p>
* <p/>
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.<p>
* <p/>
* <a href="mailto:david.whitehurst@wisplinx.com">david.whitehurst@wisplinx.com</a>
*
* @author David L. Whitehurst
* @version 1.0
* @hibernate.class table="Business"
*
*/

public abstract class Business implements Serializable {

   private String businessName;
   private Long businessId;
   
   private Collection<BusinessAddress> businessAddresses;

   public Business() {
      businessAddresses = new ArrayList<BusinessAddress>();
   }

   /**
    * @hibernate.property column="BusinessName" length="60"
    *
    */
   public String getBusinessName() {
      return businessName;
   }

   public void setBusinessName(String businessName) {
      this.businessName = businessName;
   }
   /**
    * @hibernate.id generator-class="native" type="java.lang.Long"
    *               column="BusinessId" not-null="true"
    * @hibernate.generator-param name="native" value="BusinessId"   
     */
   public Long getBusinessId() {
      return businessId;
   }

   public void setBusinessId(Long businessId) {
      this.businessId = businessId;
   }


   /**
    * @hibernate.bag lazy="false" inverse="true" cascade="all"
    *                order-by="addressId desc"
    * @hibernate.collection-key column="businessId"
    * @hibernate.collection-one-to-many class="org.dlw.model.business.base.BusinessAddress"
    *
    */
   public Collection<BusinessAddress> getBusinessAddresses() {
      return businessAddresses;
   }

   public void setBusinessAddresses(Collection<BusinessAddress> businessAddresses) {
      this.businessAddresses = businessAddresses;
   }

}

package org.dlw.model.business.base;

import java.io.Serializable;


/**
* Copyright (C) 2006  David L. Whitehurst<br>
* <p/>
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
* <p/>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.<p>
* <p/>
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.<p>
* <p/>
* <a href="mailto:david.whitehurst@wisplinx.com">david.whitehurst@wisplinx.com</a>
*
* @author David L. Whitehurst
* @version 1.0
* @hibernate.class table="BusinessAddress"
*
*/
public class BusinessAddress implements Serializable {
   /**
    *
    */
   private static final long serialVersionUID = 1L;

   private Long businessAddressId;

   private String address1;

   private String address2;

   private String city;

   private String state;

   private String zip;

   private String zipExtension;
   
   private Business business;

   /**
    * @hibernate.id generator-class="native" type="java.lang.Long"
    *               column="BusinessAddressId" unsaved-value="null"
    * @hibernate.generator-param name="assigned" value="BusinessAddressId"
    */
   public Long getBusinessAddressId() {
      return businessAddressId;
   }

   public void setBusinessAddressId(Long businessAddressId) {
      this.businessAddressId = businessAddressId;
   }

   /**
    * @hibernate.property column="address1" length="40"
    *
    */
   public String getAddress1() {
      return address1;
   }

   public void setAddress1(String address1) {
      this.address1 = address1;
   }
   
   /**
    * @hibernate.property column="address2" length="40"
    *
    */
   public String getAddress2() {
      return address2;
   }

   public void setAddress2(String address2) {
      this.address2 = address2;
   }

   /**
    * @hibernate.property column="city" length="40"
    *
    */
   public String getCity() {
      return city;
   }

   public void setCity(String city) {
      this.city = city;
   }

   /**
    * @hibernate.property column=state" length="40"
    *
    */
   public String getState() {
      return state;
   }

   public void setState(String state) {
      this.state = state;
   }

   /**
    * @hibernate.property column="zip" length="40"
    *
    */
   public String getZip() {
      return zip;
   }

   public void setZip(String zip) {
      this.zip = zip;
   }
   /**
    * @hibernate.property column="zipextension" length="40"
    *
    */
   public String getZipExtension() {
      return zipExtension;
   }

   public void setZipExtension(String zipExtension) {
      this.zipExtension = zipExtension;
   }

   /**
    * @hibernate.many-to-one not-null="true"
    * @hibernate.column name="businessId"
    *
    */
   public Business getBusiness() {
      return business;
   }

   public void setBusiness(Business business) {
      this.business = business;
   }

}

package org.dlw.model.business.provider;

import java.io.Serializable;

import org.dlw.model.business.base.Business;

/**
* Copyright (C) 2006  David L. Whitehurst<br>
* <p/>
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
* <p/>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.<p>
* <p/>
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.<p>
* <p/>
* <a href="mailto:david.whitehurst@wisplinx.com">david.whitehurst@wisplinx.com</a>
*
* @author David L. Whitehurst
* @version 1.0
* @hibernate.class table="BusinessProvider"
*
*/


public class BusinessProvider extends Business implements Serializable {

   /**
    *
    */
   private static final long serialVersionUID = 1L;


}

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
           <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
           <property name="url"><value>jdbc:mysql://localhost:3306/test</value></property>
           <property name="username"><value>test</value></property>
          <property name="password"><value>test</value></property>
      </bean>
 
      <!-- Hibernate SessionFactory -->
      <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
          <property name="dataSource"><ref local="dataSource"/></property>
          <property name="mappingResources">
              <list>
                  <value>org/dlw/model/business/base/Business.hbm.xml</value>
                  <value>org/dlw/model/business/provider/BusinessProvider.hbm.xml</value>
                  <value>org/dlw/model/business/base/BusinessAddress.hbm.xml</value>
                  <value>org/dlw/model/business/base/BusinessContact.hbm.xml</value>
                  <value>org/dlw/model/people/Address.hbm.xml</value>
                  <value>org/dlw/model/people/Contact.hbm.xml</value>
              </list>
          </property>
          <property name="hibernateProperties">
          <props>
              <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
              <prop key="hibernate.hbm2ddl.auto">update</prop>
              <prop key="show_sql">true</prop>
          </props>
          </property>
      </bean>
   <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="mySessionFactory"/>
   </bean>
   <bean id="BusinessProviderService" class="org.dlw.service.business.provider.BusinessProviderServiceImpl">
       <property name="transactionManager" ref="txManager"/>
       <property name="businessProviderDao" ref="BusinessProviderDao"/>
       <property name="businessAddressDao" ref="BusinessAddressDao"/>
    </bean>
   <bean id="BusinessProviderDao" class="org.dlw.service.business.provider.BusinessProviderDaoImpl">
       <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>
   <bean id="BusinessAddressDao" class="org.dlw.service.business.base.BusinessAddressDaoImpl">
       <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>
   <bean id="BusinessContactDao" class="org.dlw.service.business.base.BusinessContactDaoImpl">
       <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>

  </beans>

package org.dlw.service.business.provider;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.dlw.model.business.base.BusinessAddress;
import org.dlw.model.business.provider.BusinessProvider;
import org.dlw.service.business.base.BusinessAddressDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import junit.framework.TestCase;

/**
* Copyright (C) 2006 David L. Whitehurst<br>
* <p/> This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any
* later version.
* <p>
* <p/> This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* <p>
* <p/> You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* <p>
* <p/> <a
* href="mailto:david.whitehurst@wisplinx.com">david.whitehurst@wisplinx.com</a>
*
* @author David L. Whitehurst
* @version 1.0
*/
public class BusinessProviderTest extends TestCase {
   /**
    * private member variables
    */
   private ApplicationContext ctx = null;

   private BusinessProviderDao dao = null;
   
   //private BusinessAddressDao addressDao = null;
   
   
   private BusinessProvider businessProvider = null;
   private BusinessProviderService businessProviderService = null;
   
   private BusinessAddress businessAddress = null;

   private Logger log;

   /**
    * @param arg0
    */
   public BusinessProviderTest(String arg0) {
      super(arg0);
      String[] paths = { "applicationContext.xml" };
      ctx = new ClassPathXmlApplicationContext(paths);
   }

   /* (non-Javadoc)
    * @see junit.framework.TestCase#setUp()
    */
   protected void setUp() throws Exception {
      super.setUp();
      String log4jConfig = new String("c:\\Ciber\\config\\log4j.xml");
      DOMConfigurator.configureAndWatch(log4jConfig);

      dao = (BusinessProviderDao) ctx.getBean("BusinessProviderDao");
      //businessProviderService = (BusinessProviderService) ctx.getBean("BusinessProviderService");
      
      log = Logger.getLogger(getClass());

   }

   /* (non-Javadoc)
    * @see junit.framework.TestCase#tearDown()
    */
   protected void tearDown() throws Exception {
      super.tearDown();
      dao = null;
   }

   /**
    * tests the creation and save of the BusinessProvider object
    * @throws Exception
    */
//   public void testSaveObject() throws Exception {
//      businessProvider = new BusinessProvider();
//      businessProvider.setBusinessName("Acme Supply Company");
//      dao.save(businessProvider);
//      assertNotNull("primary key assigned", businessProvider.getBusinessId());
//      log.info("An object was created and primary key assigned: "
//            + businessProvider.getBusinessId());
//   }
   
   /**
    * tests the ability to getAll() objects
    * @throws Exception
    */
//   public void testGetAllObjects() throws Exception {
//      List list = dao.getAll();
//      
//      for (Iterator iter = list.iterator(); iter.hasNext();) {
//         BusinessProvider businessProvider = (BusinessProvider) iter.next();
//         log.info(businessProvider.getBusinessName() + " id:" + businessProvider.getBusinessId());
//      }
//   }
   
   /**
    * tests the ability to delete specific objects
    * @throws Exception
    */
//   public void testDeleteSomeObjects() throws Exception {
//      dao.delete(new Long(1));
//      dao.delete(new Long(2));
//      
//      assertNull(dao.getBusinessProviderById(new Long(1)));
//      assertNull(dao.getBusinessProviderById(new Long(2)));
//      
//   }
   
   public void testComplicatedSave() throws Exception {
      businessProvider = new BusinessProvider();
      businessProvider.setBusinessName("Complicated Test Company");

      businessAddress = new BusinessAddress();
      businessAddress.setAddress1("123 Anywhere Lane");
      businessAddress.setCity("Norfolk");
      businessAddress.setState("Virginia");
      businessAddress.setZip("12345");
      businessAddress.setBusiness(businessProvider);
      
      businessProvider.getBusinessAddresses().add(businessAddress);

      //businessProviderService.complexSave(businessProvider, businessAddress);
      
      dao.save(businessProvider);
//      
//      assertNotNull("primary key assigned", businessProvider.getBusinessId());
//      log.info("An object was created and primary key assigned: "
//            + businessProvider.getBusinessId());
      
   }

}

org.springframework.dao.DataIntegrityViolationException: Hibernate operation: could not insert: [org.dlw.model.business.base.BusinessAddress]; SQL [insert into BusinessAddress (address1, address2, city, state, zip, zipextension, businessId) values (?, ?, ?, ?, ?, ?, ?)]; Cannot add or update a child row: a foreign key constraint fails; nested exception is java.sql.SQLException: Cannot add or update a child row: a foreign key constraint fails
java.sql.SQLException: Cannot add or update a child row: a foreign key constraint fails
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2921)
   at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1570)
   at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1085)
   at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:670)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1159)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1076)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1061)
   at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:1968)
   at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2405)
   at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:37)
   at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
   at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:269)
   at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:167)
   at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:101)
   at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)
   at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)
   at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:98)
   at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
   at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:502)
   at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:494)
   at org.hibernate.engine.CascadingAction$1.cascade(CascadingAction.java:134)
   at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:213)
   at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:157)
   at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:108)
   at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:290)
   at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:185)
   at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:160)
   at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:108)
   at org.hibernate.engine.Cascade.cascade(Cascade.java:248)
   at org.hibernate.event.def.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:410)
   at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:299)
   at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:167)
   at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:101)
   at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)
   at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)
   at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:98)
   at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
   at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:502)
   at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:494)
   at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:490)
   at org.springframework.orm.hibernate3.HibernateTemplate$18.doInHibernate(HibernateTemplate.java:693)
   at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:366)
   at org.springframework.orm.hibernate3.HibernateTemplate.saveOrUpdate(HibernateTemplate.java:690)
   at org.dlw.service.business.provider.BusinessProviderDaoImpl.save(BusinessProviderDaoImpl.java:58)
   at org.dlw.service.business.provider.BusinessProviderTest.testComplicatedSave(BusinessProviderTest.java:143)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
   at java.lang.reflect.Method.invoke(Unknown Source)
   at junit.framework.TestCase.runTest(TestCase.java:154)
   at junit.framework.TestCase.runBare(TestCase.java:127)
   at junit.framework.TestResult$1.protect(TestResult.java:106)
   at junit.framework.TestResult.runProtected(TestResult.java:124)
   at junit.framework.TestResult.run(TestResult.java:109)
   at junit.framework.TestCase.run(TestCase.java:118)
   at junit.framework.TestSuite.runTest(TestSuite.java:208)
   at junit.framework.TestSuite.run(TestSuite.java:203)
   at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:128)
   at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
   at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
   at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
   at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
   at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)


_________________
Piratepete
david.whitehurst@wisplinx.com


Top
 Profile  
 
 Post subject:
PostPosted: Wed Aug 16, 2006 10:01 pm 
Newbie

Joined: Wed Aug 16, 2006 1:13 pm
Posts: 9
Location: Oklahoma
This closes this. The error was that my parent and child objects were inherited from abstract classes. When the extensions were removed the mapping worked fine. Also, the discriminator element might have solved this too and allowed me to use inheritance.

_________________
Piratepete
david.whitehurst@wisplinx.com


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 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.