开发者

how to query specific fields in hibernate criteria

I need to fetch only specific feilds instead of all fields. All my tables has audit feilds(4) . i want that to be ommitted on the selection. how to do that from mapping. is there any other way?.

Criteria criteria = session.createCriteria(Property.class, "property")
                .createAlias("property.propertyType", "type").createAlias(
                        "property.propertyConcern", "propertyConcern",
                        CriteriaSpecification.LEFT_JOIN).createAlias(
                        "propertyConcern.concern开发者_StackOverflow社区", "concern",
                        CriteriaSpecification.LEFT_JOIN)
                        .setResultTransformer(
                        CriteriaSpecification.DISTINCT_ROOT_ENTITY);


Use a ProjectionList to return only the fields you are after.

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

The result is an array of arrays.

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

By the way, your entity name "Property" could cause confusion/conflict with the existing Hibernate class, especially since you are using Criteria.


you have to use 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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜