-->
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.  [ 2 posts ] 
Author Message
 Post subject: Find data in a Many-Many mapping
PostPosted: Wed Mar 13, 2013 7:33 am 
Newbie

Joined: Wed Mar 13, 2013 7:06 am
Posts: 4
Hi,
I have 2 Entities Prj & Emp with a many-many mapping. Below is the structure for the same
Prj
  • PrjPid
  • PrjName
  • PrjPhone
  • List<Emp> employees
Emp
  • EmpPid
  • EmpName
  • EmpPhone
  • EmpPhone
  • List<Prj> projects

I wish to retrieve a list of Project names given an Employee Name.
For the same I have written
Code:
List<String> s1 = JPA.em()
      .createQuery("SELECT project.PrjName FROM EmpOTO WHERE EmpName = ?")
      .setParameter(1, "Employee1")
      .getResultList();

However I get an error
Code:
[IllegalArgumentException: org.hibernate.QueryException: illegal attempt to dereference collection [{synthetic-alias}{non-qualified-property-ref}projects] with element property reference [PrjName] [SELECT projects.PrjName FROM ormmapping.manytomany.models.EmpMTM WHERE EmpName = ?]]

Please could somebody assist.
-S


Top
 Profile  
 
 Post subject: Re: Find data in a Many-Many mapping
PostPosted: Mon Mar 18, 2013 7:50 am 
Newbie

Joined: Wed Mar 13, 2013 7:06 am
Posts: 4
Hi,
For anybody stuck like me, here is the soln.

Code:
      String s = "";
      CriteriaBuilder cb = JPA.em().getCriteriaBuilder();
      CriteriaQuery cq = cb.createQuery();
      Root e = cq.from(EmpMTM.class);
      Join a = e.join("projects", JoinType.LEFT);
      
//      1st way
//      cq.select(a.get("PrjName"));
//      cq.where(cb.and(cb.equal(e.get("EmpName"), "Employee1")));
      
//      2nd way
      cq.select(e.get("EmpName"));
      cq.where(cb.and(cb.equal(a.get("PrjName"), "ProjectA")));
      
      Query query = JPA.em().createQuery(cq);
      List<String> result = query.getResultList();
      
      for (int i = 0; i < result.size(); i++)
      {
         s += "," + result.get(i);
      }
      return ok(s);

Ref : http://en.wikibooks.org/wiki/Java_Persistence/Criteria

-S


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