views:

257

answers:

4

Welcome,

I've some problem with Hibernate mapping.

Database structure:

TableA
 -ID_A --PK

TableB
 -ID_B --PK
 -ID_A -- FK -> TableA

TableC
 -ID_C -- PK
 -ID_A -- FK -> TableA

POJO structure:

class TableA extends Pojo {

 /*Some Fields*/

}

class TableB extends Pojo {

  TableA tableA; 

 /*Some properties*/

}

class TableC extends Pojo {

 TableA tableA;

 Collection<tableB> tableBs;

}

What i want to have is the collection of TableB elements in mapping for a TableC Pojo, the mapping key is the tableA.

This collection should be read only.

The mapping should be hbm not annotations.

I have probably done this for every possible way... the closes i get is case that when i operate on one TableC object then is everything correct but if i load the collection of them then only the last one have proper collection set.

UPDATE: Case description.

The use case 1: Loading single object of TableC

Session session = (Session) getHibernateTemplate().getSessionFactory().openSession();
SQLQuery sqlQuery = session.createSQLQuery("SELECT c.* FROM TableC c WHERE c.ID_C = 1"); //Oracle
  sqlQuery.addEntity("c", TableC.class);
return sqlQuery.list(); //Return list with sigle object of TableC

In this case everything works fine as should. The object is loaded with all data and proper items in list of TableB objects. On this object we can operate, change it and update the modifications in database.

The use case 2 Loading collections of objects

Session session = (Session) getHibernateTemplate().getSessionFactory().openSession();
SQLQuery sqlQuery = session.createSQLQuery("SELECT c.* FROM TableC c WHERE c.ID_C in (1,2)"); //Oracle
  sqlQuery.addEntity("c", TableC.class);
return sqlQuery.list(); // throws "collection is not associated with any session" 

In this case Hibernate throw an exception while retrieving next object.

*the codes are only samples, the session is closed after all.

A: 

You might have made a mistake in the codes you posted, but assuming it is correct, but your TableC class has a List of TableB, whereas your TableC database table has a FK reference to table A.

hvgotcodes
Thats the tricky point. The elements from TableB should be mached using that FK to table A for each record of Table C.
Vash
A: 

When you have a foreign key which references a nonprimary key you should use property-ref Attribute

Its documentation

The name of a property of the associated class that is joined to this foreign key

And because your Collection is immutable you should set up mutable attribute To false

Here goes your mapping

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping 
          PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt;
<!--Set up your package right here-->
<hibernate-mapping package="br.com.ar">
     <class name="Aa" table="A">
         <id name="id">
             <generator class="native"/>
         </id>
    </class>
    <class name="Bb" table="B">
         <id name="id">
             <generator class="native"/>
         </id>
         <many-to-one name="aa" column="A_ID" class="Aa"/>
    </class>
    <class name="Cc" table="C">
         <id name="id">
             <generator class="native"/>
         </id>
         <many-to-one name="aa" column="A_ID" class="Aa"/>
         <bag name="bbList" table="B" mutable="false">
             <key column="A_ID" property-ref="aa"/>
             <one-to-many class="Bb"/>
         </bag>
    </class>
</hibernate-mapping>

Each class is described as follows

br.com.ar.Aa

public class Aa {

    private Integer id;

    // getter's and setter's

}

br.com.ar.Bb

public class Bb {

    private Integer id;

    private Aa aa;

    // getter's and setter's

}

br.com.ar.Cc

public class Cc {

    private Integer id;

    private Aa aa;

    private Collection<Bb> bbList = new ArrayList<Bb>();

    // getter's and setter's

}

ADDED AS WORKAROUND

Well, let's see first use case

query = new StringBuilder().append("SELECT ")
                               .append("{cc.*} ")
                           .append("from ")
                               .append("C cc ")
                           .append("where ")
                               .append("cc.id = 1 ")
                           .toString();

You said

The object is loaded with all data and its Bb related objects. On this object we can operate, change it and update the modifications in database

As you can see, your NATIVE SQL just retrieve Cc objects. No join. But you said it retrieves all of related objects, including The bbList. If so, it occurs because you have a mapping like (Notice fetch="select" lazy="false")

<class name="Cc" table="C">
     ...
     <bag name="bbList" table="B" mutable="false" fetch="select" lazy="false">
         <key column="A_ID" property-ref="aa"/>
         <one-to-many class="Bb"/>
     </bag>
</class>

fetch="select" uses an additional select. For one-to-many and many-to-many relationship (bbList, right ???) the fetch attribute works in conjunction with the lazy attribute to determine how and when the related collection are loaded. If lazy="true" then the collection is loaded when it is accessed by the application, but if lazy="false" then Hibernate loads the collection immediately using a separate SQL SELECT statement.

But if run

query = new StringBuilder().append("SELECT ")
                               .append("{cc.*} ")
                           .append("from ")
                               .append("C cc ")
                           .append("where ")
                               .append("cc.id in (1,2) ")
                           .toString();

I get The expected

org.hibernate.HibernateException: collection is not associated with any session

Why ???

You want To join Cc and its related bbList Through A_ID column which implies The use of property-ref attribute, right ???

<class name="Cc" table="C">
     ...
     <bag name="bbList" table="B" mutable="false" fetch="select" lazy="false">
         <key column="A_ID" property-ref="aa"/>
         <one-to-many class="Bb"/>
     </bag>
</class>

It happens if you want To use A_ID as primary-key, It must be unique. Because There are a lot of aa properties with The same value, you will get this exception. The first use case does not throw any exception because you have just retrieved one entity

Workaround

Try to get one by one

List<Cc> resultList = new ArrayList<Cc>();
for (Integer id : new Integer[] {1, 2}) {
    query = new StringBuilder().append("SELECT ")
                                   .append("{cc.*} ")
                               .append("from ")
                                   .append("C cc ")
                               .append("where ")
                                   .append("cc.id = :id ")
                               .toString();

    resultList.addAll(
             session.createSQLQuery(query)
                    .addEntity("cc", Cc.class)
                    .setParameter("id", id)
                    .list());
}

Or use plain JDBC queries

Arthur Ronald F D Garcia
Can you explain why is the collection type is a `bag` rather than a `set`?
mdma
@mdma You can use a set instead. The **issue** is because Set colletcion needs a **consistent** equals and hashCode method. **Otherwise**, you will see an unexpected behavior. And as you should know, Hibernate verifies equals and hashCode method when adding or selecting an element when using a Set collection. Hibernate supports **business key** when implementing equals and hashCode method. So if using or not, is up to him (Vash)
Arthur Ronald F D Garcia
@Arthur, the solution that You proposed is working fine but only for one object, while we load list of them, we get error "org.hibernate.HibernateException: collection is not associated with any session" and only last loaded object contain the reference to the list as i was mentioned it before. And this is the thing that i want to solve. That all object has that reference.
Vash
This sounds like a lazy-loading problem. Try adding the lazy="false" attribute to the `<bag>`
mdma
@mdma: The lazy was set to false. If it was lazy problem then none of loaded objects would have set that collection and the error should goes something like this (failed to lazily initialize a collection), in moment of usage. @Arthur, could You write that mapping with that HQL ? i dont know where should i put that statement
Vash
@Artur, I'm very thankful for your effort. This is still not that what i wanted to achieve, because those information I wanted to have while object is created with out any other intergeneration. But i think that better solution is to change the logic of previous developer. And do not create the object from pojo but find to this logic some adequate place.
Vash
@Vash Can you show **in plain code** your use case ??? I just can help you if you provide more info. As you can see, The mapping fullfil your needs. But you get Exception yet. I am sure it occurs because you are trying To get some property (i suppose It is bbList) which is not been retrieved by Hibernate. If you try to get some property **outside session.openSession() and session.close()** which has not been initialized (retrieved by Hibernate), you will get HibernateException
Arthur Ronald F D Garcia
@Arthur, See Edit.
Vash
@Arthur The the situation looks like this. In Cc we have <key column="A_ID"/> so we are comparing the D_ID with C_ID not with A_ID, so none result are found when we set again the property-ref, then we back to the origin end end up with exception but for one invocation now we have not all object from B but one in amount of all. If we modify two entries changing the D_ID to be A_ID the entry is loaded, if we change another one strange thing occur because we have just loaded two equal objects.
Vash
I have double, event triple validated.. but i will look at this one more time tomorrow. As the question about the fetch="select" you had right, but i thought that this is irrelevant.
Vash
@Vash You always will get The exception when you Try to get more than one at the same time. I explained why. You should retrieve one by one instead
Arthur Ronald F D Garcia
@Arthur So i don't get what for that workaround earlier was for i thought that little trick with switched id might solve the problem. That i was surprised that is some bypass for this Hibernate bug. The first mapping provided by You was working in the same way even better ;-). I'm totally aware that I can load this one by one but this is very time consuming operation with this data what i have. Nevertheless I'm really thankful for Your time and effort. Thank You.
Vash
@Vash Thank you! :)
Arthur Ronald F D Garcia
+1  A: 

After some researches, the problem is in the Hibernate it is known as bug #HHH-2862

It is basically caused by having an eager collection where the key of the collection is not unique in the results.

When Hibernate initialize collection using 'persistenceContext.addUninitializedCollection()' and this will detect that the collection with the given key has already been added, then sets old instance to null and current to the collection. However, that collection has already been added to the persistence context by an earlier call, and when StatefulPersistenceContext.initializeNonLazyCollections() iterate over all of the collections in the persistent context calling forceInitialization() on the references hit the null reference which throws a "collection is not associated with any session" exception". And this explain why in my case only the last object has the reference and with only one everything was working fine, and yours assumptions regarding the lazy initialization problem.

Some thoughts how to bypass this bug ?

Vash
A: 

IMHO, you are not using the ORM as it is supposed to be used. Your class model looks exactly like the table structure. This must not necessarily be the case. This way, you don't benefit from a ORM.

So I suggest to put the list of B's and C's to table A. Then you can navigate wherever you want:

class A
{
 IList<B> Bs { get; private set; }
 IList<C> Cs { get; private set; }
}

class B
{
  A A { get; set; }
}

class C
{
  A A { get; set; }
}

you map it like this:

<class name="A">
  <bag name="As" class="A">
    <key column="ID_A"/>
  </bag>
  <bag name="Bs" class="B">
    <key column="ID_A"/>
  </bag>
</class>

<class name="B">
  <many-to-one name="A" class="A" column="ID_A"/>
</class>

<class name="C">
  <many-to-one name="A" class="A" column="ID_A"/>
</class>

then you can simply navigate it like this:

B b = session.Get<B>(id);
foreach(C c in b.A.Cs)
{
  // iterate C's
}

HQL Query:

SQLQuery sqlQuery = session.createQuery("FROM TableC c WHERE c.ID_C in (1,2)"); 
  • I don't know why you are using native SQL here.
  • addEntity is to add parameters to the query of the type entity (which is actually treated as its id). You don't have any parameters in your query as far as i can see.

Edit:

Query to get all B's which share the same A as a certain C:

    C c = session.Get<C>(cId);

    SQLQuery sqlQuery = session.createQuery(
@"select B
from B, C
where B.A = C.A
  and C = :c")
      .addEntity("c", c);

or shorter:

    C c = session.Get<C>(cId);

    SQLQuery sqlQuery = session.createQuery(
@"select B
from B
where B.A = :a")
      .addEntity("a", c.A);
Stefan Steinegger
@Stefan * Because what i have to do i map a PIVOT table. This is more complex to describe, this is how it should be (i think). * addEntity from org.hibernate.SQLQuery declare the a "root" entity.that query was only a example. As for the structure that You propose, You have right but is not possible to apply for this project. This is only a simply piece of whole project.
Vash
Ok, I added a query which loads all B's which share the same A of a certain C.
Stefan Steinegger

related questions