-->
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: Quering Collection of elements with a Named Query
PostPosted: Thu Feb 12, 2009 10:20 am 
Newbie

Joined: Thu Aug 07, 2008 12:03 pm
Posts: 16
Hi! I have a doubt about how to retrieve an @embeddable collection of elements with a Named Query. Let me illustrate it with an example:

Let's suposse that I have a Customer Entity which can have different addresses, forming a relation one-to-many like this:


Code:
@Entity
@Table(name="CUSTOMERS")
public class Customer implements ICustomer{

  .. id and other columns...

       @org.hibernate.annotations.CollectionOfElements(fetch=FetchType.LAZY, targetElement=Address.class)
   @JoinTable(
         name = "ADDRESSES",
         joinColumns = @JoinColumn(name = "customer_id")
   )
   private List<IAddress> addressses= new ArrayList<IAddress>();
}


Code:
@Embeddable
public class Address implements IAddress{
    ... columns...
}



Adress isn't an entity, it's an embeddable class and therefore cannot be queried with an Named Query, Am I right?

How would you type etrieve, for example, all addresses? Would you use a "native" sql query?


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 12, 2009 11:17 am 
Newbie

Joined: Thu Aug 07, 2008 12:03 pm
Posts: 16
I found a solution to the problem of querying embeddabled objects (collections) with named querys that works for me. It uses a select of collection of scalars and then Hibernate map them into the non-entity object.

Code:

@NamedQuery(name="Adress.findAll",
             query="SELECT a.field1 as field1, ... ,  a.fieldn as fieldn FROM Customer AS c JOIN c.address AS a WHERE .....")



Then in code:

Code:
return session.getNamedQuery("Adress.findAll")
               .setResultTransformer(org.hibernate.transform.Transformers.aliasToBean(Adress.class))
               .list();


Notice the AS in SELECT a.fieldx as fieldx. Otherwise Hibernate will map them with numbers (0, 1, 2, ...) and won't be able to apply the transformer.

Hope it helps to anyone.


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.