【问题标题】:how to query specific fields in hibernate criteria如何查询休眠条件中的特定字段
【发布时间】:2010-08-30 11:44:27
【问题描述】:

我只需要获取特定字段而不是所有字段。我所有的表都有 audit feilds(4) 。我希望在选择时省略这一点。如何从映射中做到这一点。有没有其他办法?

Criteria criteria = session.createCriteria(Property.class, "property")
                .createAlias("property.propertyType", "type").createAlias(
                        "property.propertyConcern", "propertyConcern",
                        CriteriaSpecification.LEFT_JOIN).createAlias(
                        "propertyConcern.concern", "concern",
                        CriteriaSpecification.LEFT_JOIN)
                        .setResultTransformer(
                        CriteriaSpecification.DISTINCT_ROOT_ENTITY);

【问题讨论】:

    标签: hibernate


    【解决方案1】:

    使用ProjectionList 仅返回您所关注的字段。

    Criteria criteria = session.createCriteria(Property.class, "property")
        .setProjection(Projections.projectionList()
            .add(Projections.property("property.field1"))
            .add(Projections.property("concern.field2"))
            /*etc*/)
        /*etc etc etc*/;
    

    结果是一个数组。

    for (Object result : criteria.list()) {
        final Object[] fields = (Object[]) result;
        log.info("property.field1={}, concern.field2={}", fields[0], fields[1]);
    }
    

    顺便说一句,您的实体名称“Property”可能会导致与现有 Hibernate 类的混淆/冲突,尤其是在您使用 Criteria 时。

    【讨论】:

    • 但是,我需要再次迭代返回的项目以形成对象层次结构。有没有其他办法代替呢?
    【解决方案2】:

    你必须使用Transformers.aliasToBean(Property.class)..

    ProjectionList properties = Projections.projectionList();
    properties.add(Projections.property("p.id"), "id");//"id" should match with the property name to call setters
    properties.add(Projections.property("p.fname"), "fname");
    properties.add(Projections.property("s.lname"), "lname");
    
    
    criteria.setProjection(properties);
    criteria.setResultTransformer(Transformers.aliasToBean(Student.class));
    List<Student> students = (List<Student>) criteria.list();
    

    【讨论】:

      猜你喜欢
      • 2012-07-22
      • 2011-06-08
      • 1970-01-01
      • 2016-08-25
      • 2011-06-06
      • 2011-04-13
      • 2017-03-21
      相关资源
      最近更新 更多