How to return an entity with chosen columns using Criteria
Asked Answered
C

3

28

I'm really new with Hibernate. I want a List<User> using hibernate criteria, but only with fields User id and name filled up. Is that possible? Something like the query shown below:

SELECT user.id, user.name FROM user

Regards.

Cantilever answered 4/6, 2009 at 13:48 Comment(0)
A
57

This is exactly what projections are for. Here is an example:

  Criteria cr = session.createCriteria(User.class)
    .setProjection(Projections.projectionList()
      .add(Projections.property("id"), "id")
      .add(Projections.property("Name"), "Name"))
    .setResultTransformer(Transformers.aliasToBean(User.class));

  List<User> list = cr.list();

In fact, if you look at the documentation for "lazy property fetching" they specifically say:


"A different (better?) way to avoid unnecessary column reads, at least for read-only transactions is to use the projection features of HQL or Criteria queries. This avoids the need for buildtime bytecode processing and is certainly a preferred solution."


By the way, there is a related question that you may also be interested in: Hibernate Query By Example and Projections

Architectonic answered 4/6, 2009 at 21:43 Comment(1)
Is it possible to do it via HQL querry?Gate
G
3

I'm really late answering this, but, you can add a custom result transformer to the Query object like below.

Query query = session
        .getNamedQuery(
                "someNamedQueryWhichISHQL")
        .setString("cod", "10")
        .setResultTransformer(new ResultTransformer() {

            public Object transformTuple(Object[] row, String[] arg1) {
                User usr = new User(row[0],row[1]);
                return usr
            }

            public List transformList(List arg0) {

                return arg0;
            }
        });
return query.list();
Gumbo answered 10/2, 2014 at 19:58 Comment(0)
I
1

Typically you don't want to partially load the properties of an object. But if you must, see this:

http://docs.jboss.org/hibernate/stable/core/manual/en-US/html/performance.html#performance-fetching-lazyproperties

For plain reporting-like behaviour you could use entity queries:

sess.createSQLQuery("SELECT ID, NAME, BIRTHDATE FROM CATS").addEntity(Cat.class);

http://docs.jboss.org/hibernate/stable/core/manual/en-US/html/querysql.html#d0e17633

Iddo answered 4/6, 2009 at 14:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.