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.
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 ?
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">
<!--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
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.
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);
精彩评论