-->
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.  [ 12 posts ] 
Author Message
 Post subject: Problem with HQL and one-to-many
PostPosted: Fri Jun 02, 2006 9:32 am 
Senior
Senior

Joined: Wed Sep 24, 2003 3:01 pm
Posts: 158
Location: Bragan�a Paulista - Brasil
Hi all,

Hibernate version:2.1.4

I´m trying to do the following query:

Code:
from Company c
left join fetch c.companyAccounts ca
left join fetch ca.bank b
left join fetch ca.companyAccountStatus caSt
left join fetch c.companyQueues cq
left join fetch cq.companyQueueStatus cqSt
left join fetch cq.companyQueueType cqTp
left join fetch c.companyRepresentatives cr


but, when I try join the lists companyAccounts, companyQueues and
companyRepresentatives doesn´t work fine, causing the

Code:
com.sun.jdi.InvocationException occurred invoking method.


When I do the query with only on list, it´s work:

Code:
from Company c
left join fetch c.companyAccounts ca

or

from Company c
left join fetch c.companyQueues cq

or

from Company c
left join fetch c.companyRepresentatives cr


but with the 3 lists, doesn´t work.

What´s the matter with this code???

thank you!!!!

_________________
Tads


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 02, 2006 12:00 pm 
Senior
Senior

Joined: Wed Sep 24, 2003 3:01 pm
Posts: 158
Location: Bragan�a Paulista - Brasil
When I try to get the elements of the list occurs the exception:

Code:
java.lang.reflect.InvocationTargetException
   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:324)
   at br.com.pamcary.j2ee.pamcard.web.struts.action.AbstractAction.execute(AbstractAction.java:116)
   at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419)
   at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)
   at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
   at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
   at br.com.pamcary.j2ee.pamcard.web.filter.AccessFilter.doFilter(AccessFilter.java:180)
   at br.com.pamcary.j2ee.pamcard.web.filter.AccessFilter.doFilter(AccessFilter.java:78)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
   at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
   at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
   at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:198)
   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152)
   at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
   at org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:66)
   at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
   at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:158)
   at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
   at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
   at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:118)
   at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
   at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
   at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
   at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
   at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929)
   at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160)
   at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799)
   at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705)
   at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577)
   at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683)
   at java.lang.Thread.run(Thread.java:534)
Caused by: net.sf.hibernate.LazyInitializationException: Failed to lazily initialize a collection - no session or session was closed
   at net.sf.hibernate.collection.PersistentCollection.initialize(PersistentCollection.java:209)
   at net.sf.hibernate.collection.PersistentCollection.read(PersistentCollection.java:71)
   at net.sf.hibernate.collection.Bag.size(Bag.java:232)
   at br.com.pamcary.j2ee.pamcard.web.struts.action.register.RegisterCompanyAction.executeFind(RegisterCompanyAction.java:214)
   ... 43 more


I need to access the elements of the lists, but LazyInitializationException.
Bu I´m using left join FETCH for the lists.

thanks!!!!

_________________
Tads


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 02, 2006 1:16 pm 
Expert
Expert

Joined: Thu May 26, 2005 9:19 am
Posts: 262
Location: Oak Creek, WI
Hi,

Can you set the lazy="true" in the mappings or u can intialize the objects u want as

Hibernate.initialize(companyAccounts List);

_________________
RamnathN
Senior Software Engineer
http://www.linkedin.com/in/ramnathn
Don't forget to rate.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 02, 2006 1:42 pm 
Regular
Regular

Joined: Mon May 22, 2006 2:30 pm
Posts: 74
The underlying problem is that there isn't a current Hibernate Session. You would have to provide your code for us to diagnose it. But apparently you didn't create a Session, or a Session was closed. I'm guessing that you had a session, loaded the main object with the associated list set to lazing loading. The objects in the list were never loaded and the session was closed. Then you attempted to access the list, so Hibernate attempted to load it at that point.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 02, 2006 2:36 pm 
Senior
Senior

Joined: Wed Sep 24, 2003 3:01 pm
Posts: 158
Location: Bragan�a Paulista - Brasil
Hi,

I pass like parameter the query (my first post) calling
the following method to find:

Code:
    /**
     * Creates query to find a list of objects from database.
     *
     * @param query
     *
     * @return
     *
     * @throws Exception
     */
    public ArrayList createQuery(String query) throws Exception
    {
      ArrayList list = null;
      Session session = null;
      Transaction tx = null;      
      
      session = openSession();
            
       try
       {          
         tx = session.beginTransaction();          
          
           Query q = session.createQuery(query);
   
           list = (ArrayList) q.list();
          
         tx.commit();
         session.flush();          
       }
      catch (Exception e)
      {
         try
         {
            this.rollback(tx);
         }
         catch (HibernateException e1)
         {
            throw e1;
         }

         throw e;
      }
      finally
      {
         try
         {
            session.close();
         }
         catch (HibernateException e1)
         {
            throw e1;
         }
      }

        return list;
    }



when creates the query with fetch, the session is opened and transaction too.

In other similiar HQL it´s works, but in this case not.

thank U very much for your attention.

_________________
Tads


Top
 Profile  
 
 Post subject:
PostPosted: Sat Jun 03, 2006 2:13 am 
Expert
Expert

Joined: Thu May 26, 2005 9:19 am
Posts: 262
Location: Oak Creek, WI
Hi,

The error LazyInitializationException says that the collections are not loaded.
Could provide us the mapping? I don't see anything useful in the code segment.

_________________
RamnathN
Senior Software Engineer
http://www.linkedin.com/in/ramnathn
Don't forget to rate.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 05, 2006 7:50 am 
Senior
Senior

Joined: Wed Sep 24, 2003 3:01 pm
Posts: 158
Location: Bragan�a Paulista - Brasil
Hi,

Follows the mapping:

Code:
<hibernate-mapping>
    <class name="br.com.pamcary.j2ee.pamcard.model.manager.Company" table="empresa"
       proxy="br.com.pamcary.j2ee.pamcard.model.manager.Company">
      <id name="idCompany" column="id_empresa">
         <generator class="assigned"/>
      </id>
        <bag name="companyAccounts" inverse="true" lazy="true">
         <key column="id_empresa"/>
         <one-to-many class="br.com.pamcary.j2ee.pamcard.model.manager.CompanyAccount"/>
        </bag>

        <bag name="companyRepresentatives" inverse="true" lazy="true">
         <key column="id_empresa"/>
         <one-to-many class="br.com.pamcary.j2ee.pamcard.model.manager.CompanyRepresentative"/>
        </bag>

        <bag name="companyQueues" inverse="true" lazy="true">
         <key column="id_empresa"/>
         <one-to-many class="br.com.pamcary.j2ee.pamcard.model.manager.CompanyQueue"/>
        </bag>
       
    </class>

</hibernate-mapping>

<hibernate-mapping>
    <class name="br.com.pamcary.j2ee.pamcard.model.manager.CompanyAccount" table="conta_empresa"
       proxy="br.com.pamcary.j2ee.pamcard.model.manager.CompanyAccount">
      <composite-id>
          <key-many-to-one name="bank" column="nr_banco"
           class="br.com.pamcary.j2ee.pamcard.model.manager.Bank"/>
          <key-property name="nbAgency" column="agencia"/>
          <key-property name="nbAccount" column="nr_conta"/>
       </composite-id>
       <many-to-one name="company" column="id_empresa" outer-join="false"
         class="br.com.pamcary.j2ee.pamcard.model.manager.Company"/>        
      <property name="fgAccount" column="fg_conta"/>
        <many-to-one name="companyAccountStatus" column="id_conta_empresa_status" outer-join="false"
         class="br.com.pamcary.j2ee.pamcard.model.manager.CompanyAccountStatus"/>   
    </class>
</hibernate-mapping>

<hibernate-mapping>
    <class name="br.com.pamcary.j2ee.pamcard.model.manager.CompanyAccountStatus" table="conta_empresa_status"
       proxy="br.com.pamcary.j2ee.pamcard.model.manager.CompanyAccountStatus">
      <id name="idCompanyAccountStatus" column="id_conta_empresa_status">
         <generator class="assigned"/>
      </id>       
      <property name="dsCompanyAccountStatus" column="ds_conta_empresa_status"/>
        <bag name="companyAccounts" inverse="true" lazy="true">
         <key column="id_conta_empresa_status"/>
         <one-to-many class="br.com.pamcary.j2ee.pamcard.model.manager.CompanyAccount"/>
        </bag>      
    </class>

</hibernate-mapping>

<hibernate-mapping>
    <class name="br.com.pamcary.j2ee.pamcard.model.manager.Bank" table="banco"
        proxy="br.com.pamcary.j2ee.pamcard.model.manager.Bank">
      <id name="nbBank" column="nr_banco">
         <generator class="assigned"/>
      </id>   
        <property name="digBank" column="dig_banco"/>
        <property name="naBank" column="no_banco"/>
        <bag name="companyAccounts" inverse="true" lazy="true">
         <key column="nr_banco"/>
         <one-to-many class="br.com.pamcary.j2ee.pamcard.model.manager.CompanyAccount"/>
        </bag>
        <one-to-one name="bankBilletConfig" class="br.com.pamcary.j2ee.pamcard.model.manager.BankBilletConfig"
            constrained="false" outer-join="true"/>   
        <many-to-one name="bankStatus" column="id_banco_status" outer-join="false"
         class="br.com.pamcary.j2ee.pamcard.model.manager.BankStatus"/>    
      <bag name="companyQueues" inverse="true" lazy="true">
         <key column="nr_banco"/>
         <one-to-many class="br.com.pamcary.j2ee.pamcard.model.manager.CompanyQueue"/>
        </bag>
    </class>
</hibernate-mapping>

<hibernate-mapping>
    <class name="br.com.pamcary.j2ee.pamcard.model.manager.BankBilletConfig" table="config_banco_boleto"
        proxy="br.com.pamcary.j2ee.pamcard.model.manager.BankBilletConfig">
       <id name="nbBank" column="nr_banco">
           <generator class="foreign">
              <param name="property">bank</param>
           </generator>
         </id>
         <one-to-one constrained="true" outer-join="false" name="bank"
            class="br.com.pamcary.j2ee.pamcard.model.manager.Bank"/>   
        <property name="referenceDate" column="dt_referencia"/>
        <property name="wallet" column="carteira"/>         
        <property name="currencyCode" column="cd_moeda"/>         
        <property name="currencyName" column="no_moeda"/>         
        <property name="accepted" column="aceite"/>
        <property name="parcel" column="parcela"/>
        <property name="speciesDocument" column="especie_documento"/>
        <property name="placePayment" column="local_pagamento"/>
    </class>
</hibernate-mapping>

<hibernate-mapping>
    <class name="br.com.pamcary.j2ee.pamcard.model.manager.BankStatus" table="banco_status"
        proxy="br.com.pamcary.j2ee.pamcard.model.manager.BankStatus">
      <id name="idBankStatus" column="id_banco_status">
         <generator class="assigned"/>
      </id>   
        <property name="dsBankStatus" column="ds_banco_status"/>
        <bag name="banks" inverse="true" lazy="true">
         <key column="id_banco_status"/>
         <one-to-many class="br.com.pamcary.j2ee.pamcard.model.manager.Bank"/>
        </bag> 
    </class>
</hibernate-mapping>

<hibernate-mapping>
    <class name="br.com.pamcary.j2ee.pamcard.model.manager.CompanyQueue" table="fila_empresa"
       proxy="br.com.pamcary.j2ee.pamcard.model.manager.CompanyQueue">
      <id name="idCompanyQueue" column="id_fila_empresa">
         <generator class="native">
            <param name="sequence">seq_fila_empresa</param>
         </generator>
      </id>     
      <many-to-one name="company" column="id_empresa" outer-join="false"
         class="br.com.pamcary.j2ee.pamcard.model.manager.Company"/>
      <many-to-one name="bank" column="nr_banco" outer-join="true"
         class="br.com.pamcary.j2ee.pamcard.model.manager.Bank"/> 
      <property name="dtCompanyQueue" column="dt_fila_empresa"/>
      <many-to-one name="companyQueueStatus" column="id_fila_empresa_status" outer-join="false"
         class="br.com.pamcary.j2ee.pamcard.model.manager.CompanyQueueStatus"/>
      <many-to-one name="companyQueueType" column="id_fila_empresa_tipo" outer-join="false"
         class="br.com.pamcary.j2ee.pamcard.model.manager.CompanyQueueType"/>
    </class>
</hibernate-mapping>

<hibernate-mapping>
    <class name="br.com.pamcary.j2ee.pamcard.model.manager.CompanyQueueStatus" table="fila_empresa_status"
       proxy="br.com.pamcary.j2ee.pamcard.model.manager.CompanyQueueStatus">
      <id name="idCompanyQueueStatus" column="id_fila_empresa_status">
         <generator class="assigned"/>
      </id>       
      <property name="dsCompanyQueueStatus" column="ds_fila_empresa_status"/>
        <bag name="companyQueues" inverse="true" lazy="true">
         <key column="id_fila_empresa_status"/>
         <one-to-many class="br.com.pamcary.j2ee.pamcard.model.manager.CompanyQueue"/>
        </bag>      
    </class>

</hibernate-mapping>

<hibernate-mapping>
    <class name="br.com.pamcary.j2ee.pamcard.model.manager.CompanyQueueType" table="fila_empresa_tipo"
       proxy="br.com.pamcary.j2ee.pamcard.model.manager.CompanyQueueType">
      <id name="idCompanyQueueType" column="id_fila_empresa_tipo">
         <generator class="assigned"/>
      </id>       
      <property name="dsCompanyQueueType" column="ds_fila_empresa_tipo"/>
        <bag name="companyQueues" inverse="true" lazy="true">
         <key column="id_fila_empresa_tipo"/>
         <one-to-many class="br.com.pamcary.j2ee.pamcard.model.manager.CompanyQueue"/>
        </bag>      
    </class>

</hibernate-mapping>

<hibernate-mapping>
    <class name="br.com.pamcary.j2ee.pamcard.model.manager.CompanyRepresentative" table="representante_empresa"
       proxy="br.com.pamcary.j2ee.pamcard.model.manager.CompanyRepresentative">         
       <id name="idCompanyRepresentative" column="id_representante_empresa">
         <generator class="native">
            <param name="sequence">seq_representante_empresa</param>
         </generator>
      </id>          
      <property name="cpf" column="cpf"/>
      <property name="name" column="nome"/>
      <many-to-one name="company" column="id_empresa" outer-join="false"
         class="br.com.pamcary.j2ee.pamcard.model.manager.Company"/>
    </class>
</hibernate-mapping>


I´m looking for any diff or error on the mapping, but I´m not found
nothing yet.

thank U

_________________
Tads


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 05, 2006 1:49 pm 
Senior
Senior

Joined: Wed Sep 24, 2003 3:01 pm
Posts: 158
Location: Bragan�a Paulista - Brasil
It´s very strange.

The HQL only works when I use debug mode and I enter in the method where I open Session and, before I close this session, I enter in the list of returned objects. :-(

_________________
Tads


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 05, 2006 2:00 pm 
Regular
Regular

Joined: Mon May 22, 2006 2:30 pm
Posts: 74
That's not strange. That is completely consistent with how it should behave. Like I mentioned in my previous post, you have to access the list within the session if the mapping indicates the list should be loaded lazily. What you are doing is loading the parent object in the session, closing the session without accessing the list, then attempting to access the list outside the session, even though it was never loaded. You have to load it within the session, or set lazy to false in the mapping.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 05, 2006 3:04 pm 
Senior
Senior

Joined: Wed Sep 24, 2003 3:01 pm
Posts: 158
Location: Bragan�a Paulista - Brasil
Hi,

In the Hibernate in Action book (page 261), I saw the following:

Code:
Hibernate currently limits you to fetching just one collection eagerly. This is a reasonable
restriction, since fetching more than one collection in a single
query would be a Cartesian product result. This restriction might be relaxed
in a future version of Hibernate, but we encourage you to think about the
size of the result set if more than one collection is fetched in an outer join.
The amount of data that would have to be transported between database
and application can easily grow into the megabyte range, and most of it
262 CHAPTER 7
Retrieving objects efficiently
would be thrown away immediately (Hibernate flattens the tabular result set
to build the object graph). You may fetch as many one-to-one or many-toone
associations as you like.


When I fetch only on collection, it works fine. Else, not.

thanks!!!!

_________________
Tads


Top
 Profile  
 
 Post subject: Persisting one-to-many object
PostPosted: Wed Jun 07, 2006 4:08 am 
Newbie

Joined: Thu Jun 01, 2006 2:06 am
Posts: 5
Hi,

I'm using <sql-insert> statement to store the one-to-many relationship.
But its able to insert record on Master table only.

Instead of calling the <sql-insert> statement from the child hbm file, its generating update query on its own for the Detail table. Could any one help to fix this issue...

Thank you,
Mani

Below is the code snippet

Parent Object
----------------
public class EncryptedData implements Serializable {

private String userName;
private String dataToEncrypt;

private Set childSet = null;
}

Child Object
---------------
public class Child implements Serializable {
private String childName;
private String childData;
private EncryptedData encryptedData = null;
}

DAO Call
-----------
encryptedData = new EncryptedData();
encryptedData.setUserName("User Name Column");
encryptedData.setDataToEncrypt("Encrypted data");

Child child = new Child();
child.setChildName("C1");
child.setChildData("Name");

Set childSet = new HashSet();
for (int i=0; i<10; i++) {
childSet.add(child);
}

encryptedData.setChildSet(childSet);
hibernateSession.save(encryptedData);

EncryptedData.hbm.xml
----------------------------
<hibernate-mapping>
<class name="com.test.EncryptedData" table="HIBERNATE_TEST" schema="iris01" lazy="false">
<id name="userName" type="java.lang.String"
unsaved-value="null">
<column name="USERNAME" precision="15" scale="0" />
</id>


<set name="childSet" inverse="true" lazy="false" cascade="save-update" >
<key>
<column name="USERNAME" precision="15" scale="0" />
</key>
<one-to-many class="com.test.Child" />
</set>

<property name="dataToEncrypt" type="java.lang.String" column="DATA"/>

<sql-insert>INSERT INTO HIBERNATE_TEST(KEYVALUE, TIMETAKEN, DATA, A, B, C, D, USERNAME)
VALUES (Toolkit.encrypt(?,'12345678'),?)
</sql-insert>


Child.hbm.xml
------------------
<class name="com.test.Child" table="CHILD_TABLE" schema="iris01" lazy="false">
<id name="childName" type="java.lang.String" unsaved-value="null">
<column name="CHILD_NAME" precision="15" scale="0" />
</id>

<many-to-one name="encryptedData" class="com.test.EncryptedData" column="userName" lazy="false" />

<property name="childData" type="java.lang.String" column="CHILD_DATA"/>


<sql-insert>INSERT INTO CHILD_TABLE(USERNAME,CHILD_DATA,CHILD_NAME)
VALUES (?,?,?)
</sql-insert>


Problem:
----------
<sql-insert> from the child.hbm.xml is not executed, insted hibernate generates update query on its own since USERNAME exists.

USERNAME - is the foreign key in CHILD_TABLE.


Top
 Profile  
 
 Post subject: Persisting one-to-many
PostPosted: Wed Jun 07, 2006 4:09 am 
Newbie

Joined: Thu Jun 01, 2006 2:06 am
Posts: 5
Moved


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