Question

I am using Spring and Hibernate.

NamedQuery:

@NamedQueries({ @NamedQuery(name = "Contact.findByUserId", query = "select cntct.mobileNo,cntct.homeTown,cntct.city,cntct.state,cntct.country,mbr.firstName,mbr.lastName,usr.userName from Contact cntct,Member mbr,User usr where cntct.user = :user")})

@Entity
@Table(name = "Contact")
public class Contact {

@Id
@Column(name="CONTACT_ID")
@GeneratedValue(strategy=GenerationType.AUTO)  
private long contactId;

@Column(name="MOBILE_NUMBER", length=30)
private long mobileNo;

@Column(name="HOME_TOWN", length=30)
private String  homeTown;

@Column(name="CITY_NAME", length=30)
private String  city;

@Column(name="STATE_NAME", length=30)
private String  state;

@Column(name="COUNTRY_NAME", length=30)
private String  country;

The following code for firing the query and fetching the data.

public ContactView getContact(long userId) {
    Session session=sessionFactory.openSession();
    Query query=session.getNamedQuery("Contact.findByUserId");

    query.setLong("user", userId);

    List<?> list=query.list();


    session.close();
    return null;
}

The problem that I am facing is, how to map the list's data to any custom Bean?

Or is there any other viable means?

Thanks!!

Was it helpful?

Solution

query.list();

Returns the query results as a List. If the query contains multiple results per row, the results are returned in an instance of Object[].

source: http://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/Query.html#list()

So, we need to modify our code in following way to get the intended result:

List<Object[]> list=query.list();

for(i=0;i<list.size();i++){

   Object obj[]=list.get(i);

   for(Object obj1:obj){
    //set your beans by using appropriate setters
   }    
}

Other alternative:

Please use ResultTransformer in hibernate to map the resultset(of a complex select query) to a single entity class.

 ProdEntity prod = (ProdEntity)session.createQuery("select e.productId as pId,e.price as pPrice from Product e where e.productId = :productId").setParameter("productId", 103).setResultTransformer(Transformers.aliasToBean(ProdEntity.class)).uniqueResult();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top