猿问

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

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


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


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

    }

但是我收到的数据列表没有按我的需要在班级中分组。


紫衣仙女
浏览 160回答 2
2回答

HUX布斯

您的问题不是很清楚,尤其是在您尝试使用的地方,Restrictions.eq("EntityTwo", EntityTwo)因为这样不会给出正确的结果。但是,Hibernate提供了EntityOne一种从使用HibernateTransformers类选择的列中作为对象返回的方法。对于您的情况,您将需要使用要getter setter返回的列编写一个自定义类。请注意,变量的名称必须与别名列完全一样,这一点很重要。由于您的示例不清楚,所以让我用一个简单的示例进行说明:假设我需要OrderAmount按OrderDate和分组的所有购买OrderNumber&nbsp;public static List<YourCustomEntity> getAggregateOrders(){&nbsp; &nbsp; Session session = HibernateUtil.getSessionFactory().openSession();&nbsp; &nbsp; Transaction tx = null;&nbsp; &nbsp; List<YourCustomEntity> list =&nbsp; new ArrayList<YourCustomEntity>();&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; tx = session.beginTransaction();&nbsp; &nbsp; &nbsp; &nbsp; Criteria cr = session.createCriteria(PurchaseOrders.class);&nbsp; &nbsp; &nbsp; &nbsp; cr.setProjection(Projections.projectionList()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .add(Projections.sum("orderAmount").as("sumOrderAmount"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .add(Projections.groupProperty("orderNumber").as("agOrderNumber"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .add(Projections.groupProperty("orderDate").as("agOrderDate")));&nbsp; &nbsp; &nbsp; &nbsp; cr.setResultTransformer(Transformers.aliasToBean(YourCustomEntity.class));&nbsp; &nbsp; &nbsp; &nbsp; list = (List<YourCustomEntity>) cr.list();&nbsp; &nbsp;}catch (Exception asd) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(asd.getMessage());&nbsp; &nbsp; &nbsp; &nbsp; if (tx != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tx.rollback();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } finally {&nbsp; &nbsp; &nbsp; &nbsp; session.close();&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;return list;}在这方面,您将需要您的customEntity具有上面返回的三列。例如:public class YourCustomEntity {&nbsp; &nbsp; private double sumOrderAmount;&nbsp; &nbsp; private String agOrderNumber;&nbsp; &nbsp; private Date agOrderDate;&nbsp; &nbsp;//And then the getters and setters注意:请注意,变量的命名与列别名相同。

慕田峪9158850

你应该用&nbsp;Projections.groupProperty(propertyName);criteria.setProjection(Projections.groupProperty("propertyName"));
随时随地看视频慕课网APP

相关分类

Java
我要回答