Fetching data from multiple tables in Hibernate and storing the result in a bean

半腔热情 提交于 2019-12-13 17:32:58

问题


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!!


回答1:


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();



回答2:


Use generic DAO instead see for example http://yanuar7199.wordpress.com/2013/03/30/hibernate-generic-dao-for-generic-purpose/

Define mapping for One-To-Many e.g. List of contacts in UserEntity.

http://www.dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-one-to-many-using-annotations-1.html



来源:https://stackoverflow.com/questions/21374550/fetching-data-from-multiple-tables-in-hibernate-and-storing-the-result-in-a-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!