Question

how to write queries in parent -child relationships using hibernate

Asked by: chaituu

Below is the mapping files for parnet and child tables;


Parent
*****

ID NAME
1  STEVEN
2  JOHNSON


Child
*****
ID FIRSTNAME      LASTNAME                                 PID
1  XXX                             AAA                                   1
2  YYYY                          LLL                         1
3  GGGG             JJJJ            2
4  JJJJ             BJB                                  1
5  HGHH             JUIU                          2

i have 2 qustions in this..

1.Using hibernate how to retrieve child records by passing corresponding parentid(pid);i want to know how to use hibernate in a good way?

2.how to write below queries in Hibernate??
select *  from parent p,child c where p.id=c.pid and c.pid=1



Parent.hbm.xml
**********
<?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">

<hibernate-mapping>
    <class name="com.dao.Parent" table="PARENT" schema="SCOTT">
        <id name="pid" type="java.lang.Long">
            <column name="PID" precision="6" scale="0" />
            <generator class="increment" />
        </id>
        <property name="pname" type="java.lang.String">
            <column name="PNAME" length="50" />
        </property>
        <set name="childs" inverse="true">
            <key>
                <column name="PID" precision="6" scale="0" />
            </key>
            <one-to-many class="com.dao.Child" />
        </set>
    </class>
</hibernate-mapping>

Child.hbm.xml
************
<?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">

<hibernate-mapping>
    <class name="com.dao.Child" table="CHILD" schema="SCOTT">
        <id name="cid" type="java.lang.Long">
            <column name="CID" precision="6" scale="0" />
            <generator class="increment" />
        </id>
        <many-to-one name="parent" class="com.dao.Parent" fetch="select">
            <column name="PID" precision="6" scale="0" />
        </many-to-one>
        <property name="firstname" type="java.lang.String">
            <column name="FIRSTNAME" length="12" />
        </property>
        <property name="lastname" type="java.lang.String">
            <column name="LASTNAME" length="12" />
        </property>
    </class>
</hibernate-mapping>

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-03-26 at 23:29:56ID22474234
Tags

hibernate

,

child

,

parent

Topics

J2EE Frameworks

,

Java Programming Language

Participating Experts
2
Points
500
Comments
15

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. hibernate many-to-many relationship question
    I have a many to many relationship between groups and users that I have mapped as shown at the bottom of this post. I now would like to add an additional column to the user_group database, which would need to be reflected in the set element that I use in both group and user...
  2. Hibernate Eager Fetching
    In hibernate I have a many-to-one relationship defined for CreditCardVO to CreditCardTypeVO. In essence, I need a credit card type each time I retrieve a credit card. But, I don't need it lazily. I need it immediately so that when I close the hibernate transaction and pass...
  3. No data is inserted a Hibernate question.
    I am using spring and hibernate. I have a simple table item2 and user. I could fetch the user name but I could not insert item2 data. No exception is thrown. =============================================================================== public class Item2 implements Serializ...
  4. Hibernate "Lazy Initialization error"
    I have below attached lines in my application. I have FetchType.LAZY at all @ManyToOne jpa/hibernate annotations. Now I get exception: "org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed" As I understood connect...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: mnrzPosted on 2007-03-26 at 23:41:40ID: 18798188

you may use Criteria:

Criteria c = session.createCriteria(Parent.class);
c.createAlias("childs","childs");
c.add(Expression.eq("parent.id",pid)); //pid in your case is 1
List result = c.list();

 

by: chaituuPosted on 2007-03-26 at 23:46:16ID: 18798207

c.createAlias("childs","childs");

what will it do?it will automatically join parent and child tables??

if i want outjoin on child table what should i do??

 

by: chaituuPosted on 2007-03-26 at 23:48:59ID: 18798219

what is meaning of this --- ("childs","childs")

 

by: mnrzPosted on 2007-03-27 at 00:00:01ID: 18798256

well
in your hbm you defined a one-to-many relationship

 <one-to-many class="com.dao.Child" />

so, hibernate will understand your child table

c.createAlias("childs","childs"); is just like "select * from Parent parent, Child childs"

and after that you can access all its fields by using the alias "childs", for example, "childs.firstName"

-----
for outer join, I am not sure but I think you should use this

c.createAlias("childs","childs",Criteria.LEFT_JOIN); or
c.createAlias("childs","childs",Criteria.FULL_JOIN);

 

by: chaituuPosted on 2007-03-27 at 00:06:25ID: 18798269

Criteria c  = getSession().createCriteria(Parent.class);
                   
              System.out.println("aaaaaaaaaaa11111");
            c.createAlias("childs","childs");
            System.out.println("aaaaaaaaaaa222222");
            c.add(Expression.eq("parent.pid",1));
            List results = c.list();

WHEN I execute i am getting below exception

aaaaaaaaaaa11111
aaaaaaaaaaa222222
Exception in thread "main" org.hibernate.QueryException: could not resolve property: parent of: com.dao.Parent
      at org.hibernate.persister.entity.AbstractPropertyMapping.throwPropertyException(AbstractPropertyMapping.java:43)
      at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:37)
      at org.hibernate.persister.entity.AbstractEntityPersister.getSubclassPropertyTableNumber(AbstractEntityPersister.java:1282)
      at org.hibernate.persister.entity.BasicEntityPropertyMapping.toColumns(BasicEntityPropertyMapping.java:31)
      at org.hibernate.persister.entity.AbstractEntityPersister.toColumns(AbstractEntityPersister.java:1257)
      at org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumns(CriteriaQueryTranslator.java:433)
      at org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumnsUsingProjection(CriteriaQueryTranslator.java:393)
      at org.hibernate.criterion.SimpleExpression.toSqlString(SimpleExpression.java:45)
      at org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:333)
      at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:82)
      at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:67)
      



this is my Parent.java class
*****************************

                  public class Parent  implements java.io.Serializable {


    // Fields    

     private Long pid;
     private String pname;
     private Set childs = new HashSet(0);


    // Constructors

    /** default constructor */
    public Parent() {
    }

   
    /** full constructor */
    public Parent(String pname, Set childs) {
        this.pname = pname;
        this.childs = childs;
    }

   
    // Property accessors

    public Long getPid() {
        return this.pid;
    }
   
    public void setPid(Long pid) {
        this.pid = pid;
    }

    public String getPname() {
        return this.pname;
    }
   
    public void setPname(String pname) {
        this.pname = pname;
    }

    public Set getChilds() {
        return this.childs;
    }
   
    public void setChilds(Set childs) {
        this.childs = childs;
    }
   

}

 

by: JaaxPosted on 2007-03-27 at 00:38:09ID: 18798355

1. Firstly you it is advisable to add  your "childs" as a SET  in your parent entity - something like this in the parent hbm file
....
<set name="children">
      <key column="PID"/>
      <one-to-many class="com.dao.Child"/>
</set>
....

Also define corresponding getters and setters in the Parent.java file

Having done so, the children can be retrieved as follows in java

Parent parent = (Parent)getSessionFactory().openSession().get(com.dao.Parent.class, parentId);
Hibernate.initialize(parent .getChildren());
if(parent .getChildren() != null){
    Iterator iter = parent .getChildren().iterator();
   while(iter.hasNext()){
       Hibernate.initialize(iter.next());
  }
}


2.You can use HQL for your queries :
String query = "select * from parent p
      left outer join p.children c
where  c.pid=1";

List list = HibernateTemplate.find(query); //Use an instance of HibernateTemplate
The list contains your results in the form of list of object arrays



 

by: mnrzPosted on 2007-03-27 at 01:20:27ID: 18798444

sorry
please change this line

c.add(Expression.eq("parent.pid",1));

to

c.add(Expression.eq("pid",1));

please show your Child class

 

by: chaituuPosted on 2007-03-27 at 03:57:49ID: 18798845

jaax,

i removed Hibernate.initialize in my code its working fine;what is the use of Hibernate.initialize ??

mnrz,

if i changed it to c.add(Expression.eq("pid",new Long(1)));  its working fine.

 

by: JaaxPosted on 2007-03-27 at 04:46:26ID: 18799068

Do you mean to say that with Hibernate.initialize , your code fails - i.e; throws some kind of Hibernate Exception ?

Hibernate.initialize() initializes the entities on demand and not beforehand, thus improving performance.
If you had specified lazy="false" in your hbm file, hibernate would load all the objects in the object graph and that would consume memory but accords the client, the luxury to use any of the objects at its whim. On the other hand, specifying lazy="true", postpones loading of the entity until actually it is needed (by specifying Hibernate.initialize()) and thus economizes on memory. But on the flip-side, the clinet should be careful to use only those objects in the graph that have been initialized.

 

by: chaituuPosted on 2007-03-27 at 05:15:04ID: 18799201


i observed two things by writing in both forms.


Parent parent = (Parent)getSessionFactory().openSession().get(com.dao.Parent.class, parentId);
Hibernate.initialize(parent .getChildren());
if(parent .getChildren() != null){
    Iterator iter = parent .getChildren().iterator();
   while(iter.hasNext()){
       Hibernate.initialize(iter.next());
  }
}


from writing above code actually it execting two queries like

select parent0_.PID as PID0_0_, parent0_.PNAME as PNAME0_0_ from PARENT parent0_ where parent0_.PID=?

select childs0_.PID as PID1_, childs0_.CID as CID1_, childs0_.CID as CID1_0_, childs0_.PID as PID1_0_, childs0_.FIRSTNAME as FIRSTNAME1_0_, childs0_.LASTNAME as LASTNAME1_0_ from CHILD childs0_ where childs0_.PID=?

*******************************************************************************

but the below code executes only one query by joining two tables like....thus improving performace.


select this_.PID as PID0_1_, this_.PNAME as PNAME0_1_, childs1_.CID as CID1_0_, childs1_.PID as PID1_0_, childs1_.FIRSTNAME as FIRSTNAME1_0_, childs1_.LASTNAME as LASTNAME1_0_ from PARENT this_ inner join CHILD childs1_ on this_.PID=childs1_.PID where this_.PID=?

Criteria c  = getSession().createCriteria(Parent.class);
            c.createAlias("childs","childs");
            c.add(Expression.eq("pid",new Long(1))); //pid in your case is 1
            List results = c.list();
           
            for (Iterator iter = results.iterator(); iter.hasNext();) {
                        Child element = (Child) iter.next();
                          System.out.println("ParentDAO.findByExample()"+element.getFirstname());
                  }

Exception in thread "main" java.lang.ClassCastException: com.dao.Parent
      

but my problem is how to get only child information ;if i type cast with Parent object its working fine...but i want child objects ..


 

by: mnrzPosted on 2007-03-27 at 05:22:26ID: 18799245

so you can create your criteria with Child, check this:

List result = session.createCriteria(Child.class).
createAlias("parent","parent").
add(Expression.eq("parent.pid",new Long(1))).
list();

this will return a list of type "Child"

 

by: JaaxPosted on 2007-03-27 at 05:25:05ID: 18799259

After you have done this :

Parent parent = (Parent)getSessionFactory().openSession().get(com.dao.Parent.class, parentId);
Hibernate.initialize(parent .getChildren());
if(parent .getChildren() != null){
    Iterator iter = parent .getChildren().iterator();
   while(iter.hasNext()){
       Hibernate.initialize(iter.next());
  }
   
   Iterator iter = parent .getChildren().iterator();
  while(iter.hasNext()){
      Child child = (Child)iter.next();
     //Do what you like with child entity
    }

   
 

}


}

 

by: chaituuPosted on 2007-03-27 at 05:38:12ID: 18799345

final question for both of you which approach is better ;my personnel view is mnrz is said is better one because its executing only query gives us better performance what do you say Jaax..

 

by: mnrzPosted on 2007-03-27 at 05:45:48ID: 18799395

In my opinion, the performance in both of them is alike, but with Criteria you have many options and features you may need in the future

 

by: JaaxPosted on 2007-03-27 at 06:27:02ID: 18799630

The choice should be on the requirement. Load is useful when you are querying via PRIMARY KEY and when you are damn sure that it will result in only one record.
Criteria is mainly used for SEARCHING and as mnrz has maintained, additional search attributes can be added or removed as you like. Criteria is the Object oriented way of dealing with DB search. However, Criteria is restricted in certain aspects - like you cannot specify SQL functions and limited flexibility with joins.

To summarize:
1.If you want to load only one record based on primary key go for load or get
2.If you want to search and are expecting multiple outputs, then opt for Criteria or HQL
The choice between Criteria and HQL should be based on flexibility in terms of using advanced SQL features (HQL) and using Object oriented way of searching

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...