将数据作为自定义对象休眠条件检索



任务是从数据库中检索某些列列表的数据,并作为自定义的现有类返回。

我尝试使用以下代码解决此任务:

public List<EntityOne> getServiceProviders(EntityTwo EntityTwo) {
Criteria criteria = createCriteria(EntityOne.class);
criteria.add(Restrictions.eq("EntityTwo", EntityTwo));
criteria.createAlias("spid", "two");
criteria.addOrder(Order.asc("two.entityName"));
criteria.setProjection(Projections.projectionList()
.add(Projections.property("entityId"), "entityId")
.add(Projections.property("publishStatus"), "publishStatus")
.add(Projections.property("two.entityName"), "two.entityName")
.add(Projections.property("two.entityId"), "two.entityId")
);
return criteria.list();
}

但是我收到一个数据列表,这些数据没有按照我想要的方式分组到类中。

您的问题不是很清楚,尤其是在您尝试使用Restrictions.eq("EntityTwo", EntityTwo)的地方,因为这不会给出正确的结果。但是,Hibernate提供了一种从使用HibernateTransformers类选择的列中将EntityOne作为对象返回的方法。在您的情况下,您需要编写一个自定义类,其中包含要返回的getter setter列。请注意,变量的名称必须与别名列完全相同,这一点很重要。

由于您的示例不清楚,让我用一个简单的例子来说明:假设我需要按OrderDateOrderNumber分组的所有购买OrderAmount

public static List<YourCustomEntity> getAggregateOrders(){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
List<YourCustomEntity> list =  new ArrayList<YourCustomEntity>();
try {
tx = session.beginTransaction();
Criteria cr = session.createCriteria(PurchaseOrders.class);
cr.setProjection(Projections.projectionList()
.add(Projections.sum("orderAmount").as("sumOrderAmount"))
.add(Projections.groupProperty("orderNumber").as("agOrderNumber"))
.add(Projections.groupProperty("orderDate").as("agOrderDate")));
cr.setResultTransformer(Transformers.aliasToBean(YourCustomEntity.class));
list = (List<YourCustomEntity>) cr.list();
}catch (Exception asd) {
System.out.println(asd.getMessage());
if (tx != null) {
tx.rollback();
}
} finally {
session.close();
}
return list;
}

在这方面,您将需要您的自定义实体返回上面的三列。例如:

public class YourCustomEntity {
private double sumOrderAmount;
private String agOrderNumber;
private Date agOrderDate;
//And then the getters and setters

注意:请注意,变量的命名与列别名相同。

你应该使用Projections.groupProperty(propertyName);

criteria.setProjection(Projections.groupProperty("propertyName"));

最新更新