-->
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: Child/parent could not initialize collection exception
PostPosted: Wed Jul 29, 2009 7:03 am 
Newbie

Joined: Wed Jul 29, 2009 6:52 am
Posts: 5
I am getting the following exception:

Code:
tests:
    [junit] Running model.FolderImplTest
    [junit] Testsuite: model.FolderImplTest
    [junit] Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 3.563 sec
    [junit] Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 3.563 sec
    [junit]
    [junit] Testcase: test(model.FolderImplTest): Caused an ERROR
    [junit] could not initialize a collection: [model.Folder.children#4]
    [junit] org.hibernate.exception.SQLGrammarException: could not initialize a collection: [model.Folder.children#4]
    [junit]     at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)
    [junit]     at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    [junit]     at org.hibernate.loader.Loader.loadCollection(Loader.java:2022)
    [junit]     at org.hibernate.loader.collection.CollectionLoader.initialize(CollectionLoader.java:59)
    [junit]     at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:587)
    [junit]     at org.hibernate.event.def.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventL
istener.java:83)
    [junit]     at org.hibernate.impl.SessionImpl.initializeCollection(SessionImpl.java:1743)
    [junit]     at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:366)
    [junit]     at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:108)
    [junit]     at org.hibernate.collection.PersistentSet.iterator(PersistentSet.java:186)
    [junit]     at model.Folder.toString(Folder.java:59)
    [junit]     at model.FolderImplTestBean.test(FolderImplTestBean.java:61)
    [junit]     at model.FolderImplTestBean$$FastClassByCGLIB$$84649914.invoke(<generated>)
    [junit]     at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149)
    [junit]     at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:700)
    [junit]     at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
    [junit]     at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
    [junit]     at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    [junit]     at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:635)
    [junit]     at model.FolderImplTestBean$$EnhancerByCGLIB$$60026dde.test(<generated>)
    [junit]     at model.FolderImplTest.test(FolderImplTest.java:32)
    [junit] Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corr
esponds to your MySQL server version for the right syntax to use near 'Group group1_ on children0_.group_id=group1_.id left outer join User
user2_ on c' at line 1
    [junit]     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1026)
    [junit]     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    [junit]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3515)
    [junit]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3447)
    [junit]     at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1951)
    [junit]     at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2101)
    [junit]     at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2554)
    [junit]     at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1761)
    [junit]     at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1912)
    [junit]     at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93)
    [junit]     at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
    [junit]     at org.hibernate.loader.Loader.getResultSet(Loader.java:1808)
    [junit]     at org.hibernate.loader.Loader.doQuery(Loader.java:697)
    [junit]     at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
    [junit]     at org.hibernate.loader.Loader.loadCollection(Loader.java:2015)
    [junit]
    [junit]
    [junit] Test model.FolderImplTest FAILED


From running the following code:

Abstract base class for parents and children:

Code:
/**
*
*/
package model;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

@Entity
abstract public class Content {

   private Group group;
   
   private Long id;

   private String name;
   
   private User user;
   
   private Folder parent;
   
   private Date creationDateTime;
   
   /** Default constructor. */
   public Content() {
      group = null;
      id = null;
      name = "";
      user = null;
      parent = null;
      creationDateTime = Calendar.getInstance().getTime();      
   }
   
   public Content(Long id) {
      this.id = id;
   }
   
   public Content(String name) {
      this();
      this.name = name;
   }
   
   /* (non-Javadoc)
    * @see model.Content#getGroup()
    */
   @ManyToOne
   public Group getGroup() {
      return group;
   }

   /* (non-Javadoc)
    * @see model.Content#getId()
    */
   @Id
   @GeneratedValue(strategy=GenerationType.AUTO)
   public Long getId() {
      return id;
   }

   public void setId(long id) {
      this.id = id;
   }
   
   /* @return The name of the folder or document. */
   @Basic
   public String getName() {
      return name;
   }

   /* @return The folder that the content is held in. */
   @ManyToOne(targetEntity=model.Content.class)
   @JoinColumn(name="parent_id",nullable=true)
   public Folder getParent() {
      return parent;
   }

   
   public void setParent(Folder parent) {
      this.parent = parent;
   }
   
   /* (non-Javadoc)
    * @see model.Content#getUser()
    */
   @ManyToOne
   public User getUser() {
      return user;
   }

   /** @return The full path of the content. */
   @Transient
   public List<Content> getFullPath() {
      List<Content> fullPath;
      if (parent != null) {
         fullPath = getParent().getFullPath();         
      } else {
         fullPath = new ArrayList<Content>();         
      }
      fullPath.add(this);
      return fullPath;
   }

   public void setGroup(Group group) {
      this.group = group;
   }

   public void setName(String name) {
      this.name = name;
   }

   public void setUser(User user) {
      this.user = user;
   }
   
   public String toString(){
      String string = "";
      List<Content> fullPath = getFullPath();
      String delimiter = "";
      for (Content content : fullPath) {
         string += delimiter + content.getName();
         delimiter = "/";
      }
      return string;
   }
   
   public boolean equals(Content rhs) {
      return (getId().equals(rhs.getId()));   
   }

   @Temporal (TemporalType.TIMESTAMP)
   public Date getCreationDateTime() {
      return creationDateTime;
   }

   public void setCreationDateTime(Date creationDateTime) {
      this.creationDateTime = creationDateTime;
   }
}


Concrete parent class:

Code:
package model;

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

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.OneToMany;

@Entity
public class Folder extends Content {

   private Set<Content> children = new HashSet<Content>();
   
   public Folder() {
   }
   
   public Folder(Long id) {      
      super(id);
   }
   
   public Folder(String name) {
      super(name);
   }
   
   @OneToMany(cascade = { CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REMOVE },
         mappedBy = "parent")
   public Set<Content> getChildren() {
      return children;
   }

   public void addChild(Content child) {
      child.setParent(this);      
      children.add(child);
   }
   
   public void removeChild(Content child) {
      children.remove(child);
      child.setParent(null);
   }
   
   public String toString() {
      String string = super.toString();
      for (Content child:children) {
         string += "\n"+child.toString();
      }
      return string;
   }
   
   public void setChildren(Set<Content> children) {
      this.children = children;
   }
}


Test bean:

Code:
package model;

import org.springframework.transaction.annotation.Transactional;

import dao.ContentDao;
import model.Folder;
import static org.junit.Assert.*; // Static imports into the current namespace

/**
* @author tim
*
*/
public class FolderImplTestBean {

   private ContentDao contentDao;
   
   private Folder rootFolder;
   
   /**
    * @throws java.lang.Exception
    */
   @Transactional(readOnly=false)
   public void setUp() {
      rootFolder = new Folder("");

      Folder documentsAndSettings = new Folder("home");
      rootFolder.addChild(documentsAndSettings);

      Folder programFiles = new Folder("usr");
      rootFolder.addChild(programFiles);

      Folder tim = new Folder("tim");
      documentsAndSettings.addChild(tim);

      contentDao.insertContent(rootFolder);
   }

   /**
    * @throws java.lang.Exception
    */
   @Transactional(readOnly=false)
   public void tearDown() {
      contentDao.removeContent(rootFolder);
   }

   @Transactional(readOnly=false)
   public void test() {
      Folder retrievedRootFolder = (Folder) contentDao.findMyObjectById(rootFolder.getId());
      assertEquals(rootFolder.getId(), retrievedRootFolder.getId());
      assertEquals(rootFolder.toString(),retrievedRootFolder.toString());      
   }

   public void setContentDao(ContentDao contentDao) {
      this.contentDao = contentDao;
   }   
}


I am using MySQL 5 and Spring 2.5.
Any ideas?
Is the use of an abstract class causing problems?

Thanks in advance,

Tim.


Top
 Profile  
 
 Post subject: Re: Child/parent could not initialize collection exception
PostPosted: Wed Jul 29, 2009 8:14 am 
Newbie

Joined: Wed Jul 29, 2009 6:52 am
Posts: 5
Here is the log output. The early stuff is a bit worrying:

Code:
Jul 29 13:11:23 INFO  n.AnnotationSessionFactoryBean buildSessionFactory       Building new Hibernate SessionFactory
Jul 29 13:11:24 ERROR nate.tool.hbm2ddl.SchemaUpdate execute                   Unsuccessful: create table Group (id bigint not null auto_increment, name varchar(255), primary key (id))
Jul 29 13:11:24 ERROR nate.tool.hbm2ddl.SchemaUpdate execute                   You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Group (id bigint not null auto_increment, name varchar(255), primary key (id))' at line 1
Jul 29 13:11:24 ERROR nate.tool.hbm2ddl.SchemaUpdate execute                   Unsuccessful: alter table Content add index FK9BEFCC594E0E66F6 (group_id), add constraint FK9BEFCC594E0E66F6 foreign key (group_id) references Group (id)
Jul 29 13:11:24 ERROR nate.tool.hbm2ddl.SchemaUpdate execute                   You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Group (id)' at line 1
Jul 29 13:11:24 ERROR nate.tool.hbm2ddl.SchemaUpdate execute                   Unsuccessful: alter table Group_User add index FKC33535CB4E0E66F6 (Group_id), add constraint FKC33535CB4E0E66F6 foreign key (Group_id) references Group (id)
Jul 29 13:11:24 ERROR nate.tool.hbm2ddl.SchemaUpdate execute                   You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Group (id)' at line 1
Jul 29 13:11:24 INFO  e3.HibernateTransactionManager afterPropertiesSet        Using DataSource [org.apache.commons.dbcp.BasicDataSource@b57e9a] of Hibernate SessionFactory for HibernateTransactionManager
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager getTransaction            Creating new transaction with name [uk.co.datagraphic.cms.model.FolderImplTestBean.setUp]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager doBegin                   Opened new Session [org.hibernate.impl.SessionImpl@19b4748] for Hibernate transaction
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager doBegin                   Preparing JDBC Connection of Hibernate Session [org.hibernate.impl.SessionImpl@19b4748]
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager doBegin                   Exposing Hibernate transaction as JDBC transaction [jdbc:mysql://localhost/datagraphic, UserName=root@localhost, MySQL-AB JDBC Driver]
Jul 29 13:11:25 DEBUG m.hibernate3.HibernateTemplate doExecute                 Found thread-bound Session for HibernateTemplate
Jul 29 13:11:25 DEBUG m.hibernate3.HibernateTemplate doExecute                 Not closing pre-bound Hibernate Session after HibernateTemplate
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager processCommit             Initiating transaction commit
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager doCommit                  Committing Hibernate transaction on Session [org.hibernate.impl.SessionImpl@19b4748]
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager doCleanupAfterCompletion  Closing Hibernate Session [org.hibernate.impl.SessionImpl@19b4748] after transaction
Jul 29 13:11:25 DEBUG hibernate3.SessionFactoryUtils closeSession              Closing Hibernate Session
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager getTransaction            Creating new transaction with name [uk.co.datagraphic.cms.model.FolderImplTestBean.test]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager doBegin                   Opened new Session [org.hibernate.impl.SessionImpl@2da5a6] for Hibernate transaction
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager doBegin                   Preparing JDBC Connection of Hibernate Session [org.hibernate.impl.SessionImpl@2da5a6]
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager doBegin                   Exposing Hibernate transaction as JDBC transaction [jdbc:mysql://localhost/datagraphic, UserName=root@localhost, MySQL-AB JDBC Driver]
Jul 29 13:11:25 DEBUG m.hibernate3.HibernateTemplate doExecute                 Found thread-bound Session for HibernateTemplate
Jul 29 13:11:25 DEBUG m.hibernate3.HibernateTemplate doExecute                 Not closing pre-bound Hibernate Session after HibernateTemplate
Jul 29 13:11:25 ERROR ate.util.JDBCExceptionReporter logExceptions             You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Group group1_ on children0_.group_id=group1_.id left outer join User user2_ on c' at line 1
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager processRollback           Initiating transaction rollback
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager doRollback                Rolling back Hibernate transaction on Session [org.hibernate.impl.SessionImpl@2da5a6]
Jul 29 13:11:25 DEBUG e3.HibernateTransactionManager doCleanupAfterCompletion  Closing Hibernate Session [org.hibernate.impl.SessionImpl@2da5a6] after transaction
Jul 29 13:11:25 DEBUG hibernate3.SessionFactoryUtils closeSession              Closing Hibernate Session


Top
 Profile  
 
 Post subject: Re: Child/parent could not initialize collection exception
PostPosted: Wed Jul 29, 2009 8:26 am 
Newbie

Joined: Wed Jul 29, 2009 6:52 am
Posts: 5
The table creation fails because GROUP is a reserved word. I have overriden the default table name with 'groups' and the error disappears.

Any comments on my parent / child approach are still welcome.

Tim.


Top
 Profile  
 
 Post subject: Re: Child/parent could not initialize collection exception
PostPosted: Thu Jul 30, 2009 5:04 am 
Newbie

Joined: Wed Jul 29, 2009 6:52 am
Posts: 5
I also had to change the cascade to cascade.all to get things to work.


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.