Quantcast
Channel: Java Programming Forum - Learn Java Programming - Hibernate
Viewing all articles
Browse latest Browse all 76

Reduce number of queries when using bags

$
0
0
Code:

<hibernate-mapping package="sandbox">

  <class name="person" table="PERSON">
      <id name="id" />
      <property name="name" />

      <joined-subclass name="child" table="CHILD">
        <key column="id" />

        <bag name="certificates" table="CERTIFICATES" lazy="false"
            fetch="subselect" cascade="all">
            <key column="id" />
            <composite-element class="Certificate" >
              <property name="board" />
              <property name="grade" />
            </composite-element>
           
        </bag>

      </joined-subclass>

  </class>


</hibernate-mapping>

This is a one to many relationship. Ie each child can have multiple certificates.If my child table has 10 rows. Hibernate does 11 queries. 1 to get all the children and then 1 per child to find certificates for each child.

This does not scale very well, is there a way to reduce the queries. I have tried using different combinations of cascade/fetch/lazy etc, but have not managed to reduce the queries?


If I was to do this manually in jdbc I would query each table once and then add certificates to children:

For example:


Code:

List<Child> children = listChildren();
//map of certifcated by child id
Map<Integer,List<Certificate>> certs = listCertificates();

for(Child c: children){
c.addCertificates(certs.get(c.getId());
}

I thought I would be able to configure hibernate to do this. Is it possible?

Thanks

Chris

Viewing all articles
Browse latest Browse all 76

Trending Articles