How to return an entity with chosen columns using Criteria

前端 未结 3 949
感动是毒
感动是毒 2020-12-13 13:51

I\'m really new with Hibernate. I want a List using hibernate criteria, but only with fields User id and name filled up. Is that possible? Something

3条回答
  •  时光说笑
    2020-12-13 14:17

    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 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

提交回复
热议问题