Hibernate列表的映射

时间:2015-11-10 06:22:05

标签: java hibernate

我想从DB中检索3列。查询时检索到2行或3行。这是查询String query="select createdTime,receiptStatus,pointsEarned from Receipt where loyaltyId=:loyaltyId"; List x= (List) entityManager.createQuery(query).setParameter("loyaltyId",loyaltyId).getResultList();

我想将列映射到pojo类并传递列表(或使用该pojo的对象).i创建了一个像这样的pojo类

public class TransactionHistoryEntity 
{
	  private List<String> tranStatus;
	  private List<String> tranDate;
	  private List<String> pointsEarned;
	public List<String> getTranStatus() {
		return tranStatus;
	}
	public void setTranStatus(List<String> tranStatus) {
		this.tranStatus = tranStatus;
	}
	public List<String> getTranDate() {
		return tranDate;
	}
	public void setTranDate(List<String> tranDate) {
		this.tranDate = tranDate;
	}
	public List<String> getPointsEarned() {
		return pointsEarned;
	}
	public void setPointsEarned(List<String> pointsEarned) {
		this.pointsEarned = pointsEarned;
	}
}

创建时间应映射到tranDate,receiptstatus映射到tranStatus,pointsEarned映射到pointsEarned。

我怎样才能实现这一目标?我的查询是否正确?

1 个答案:

答案 0 :(得分:0)

Criteria cr= getCurrentSession().createCriteria(Receipt.class)
.add(Restrictions.eq("loyaltyId", loyaltyId))
.setProjection(Projections.projectionList()
.add(Projections.property("createdTime"), "createdTime")
.add(Projections.property("receiptStatus"), "receiptStatus")
.add(Projections.property("pointsEarned "), "pointsEarned "))
.setResultTransformer(Transformers.aliasToBean(Receipt.class));
List<Receipt> receiptList = cr.list();

此条件充当String query="select createdTime,receiptStatus,pointsEarned from Receipt where loyaltyId=:loyaltyId";并将返回结果映射到List<Receipt>

TransactionHistoryEntity trans = new TransactionHistoryEntity ();
List<String> tranStatus = new ArrayList<String>();
List<String> tranDate = new ArrayList<String>();
List<String> pointsEarned = new ArrayList<String>();
for(int i = 0 ; i < receiptList.size() ; i++){
   tranDate.add(receiptList.get(i).getCreatedTime());
   tranStatus.add(receiptList.get(i).getReceiptStatus());
   pointsEarned.add(receiptList.get(i).getPointsEarned());
}
TransactionHistoryEntity.setTranStatus(tranStatus);
TransactionHistoryEntity.setTranDate(tranDate);
TransactionHistoryEntity.setPointsEarned(pointsEarned)

这会将返回结果映射到TransactionHistoryEntity