且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Hibernate中从多个表中提取数据并将结果存储在一个bean中

更新时间:2023-12-01 10:53:22

  query.list(); 

以列表形式返回查询结果。如果查询每行包含多个结果,则结果将返回到Object []的实例中。

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



因此,我们需要按照以下方式修改我们的代码以获得预期结果:

  List< Object []&GT;列表= query.list(); 

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

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

for(Object obj1:obj){
//使用适当的setter设置你的bean
}
}
$ p>

其他选择:



请在hibernate中使用 ResultTransformer 结果集(复杂的选择查询)到单个实体类。

  ProdEntity prod =(ProdEntity)session.createQuery(select e.productId as pId,e.price as pPrice from Product e其中e.productId =:productId)。setParameter(productId,103).setResultTransformer(Transformers.aliasToBean(ProdEntity.class))。uniqueResult(); 


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

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