How to use hibernate criteria to return only one element of an object instead the entire object?

后端 未结 7 970
攒了一身酷
攒了一身酷 2020-12-29 19:54

I\'m trying to get only the list of id of object bob for example instead of the list of bob. It\'s ok with a HQL request, but I would know if it\'s possible using criteria ?

相关标签:
7条回答
  • 2020-12-29 20:00
    SessionFactory sessionFactory;    
    Criteria crit=sessionFactory.getCurrentSession().createCriteria(Model.class);
    crit.setProjection(Projections.property("id"));
    List result = crit.list();
    

    This code code will give you list of ids in the model class like [1,2,3]. if you wants to get the array list like [{"id":1},{"id":2}] then use the following code

    SessionFactory sessionFactory;    
    Criteria crit=sessionFactory.getCurrentSession().createCriteria(Model.class); 
    crit.setProjection(Projections.property("id").as("id")); 
    List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
    
    0 讨论(0)
  • 2020-12-29 20:04

    Another option (though a bit un hibernate-esque) is to use "raw" sql, like this:

    List<Long> myList = session.createSQLQuery("select single_column from table_name")
              .addScalar("single_column", StandardBasicTypes.LONG).list();
    
    0 讨论(0)
  • 2020-12-29 20:09

    I think you could do that with Projections, something like

    Criteria.forClass(bob.class.getName())
            .add(Restrictions.gt("id", 10))
            .setProjection(Projections.property("id"))
            );
    
    0 讨论(0)
  • 2020-12-29 20:12

    You can do that like this

        bob bb=null;
    
        Criteria criteria = session.createCriteria(bob.class);  
        criteria.add(Restrictions.eq("id",id));
    
        bb = (bob) criteria.uniqueResult();
    

    as Restrictions you can add your condition

    0 讨论(0)
  • 2020-12-29 20:13

    or setProjection(Projections.id())

    0 讨论(0)
  • 2020-12-29 20:15

    http://www.devarticles.com/c/a/Java/Hibernate-Criteria-Queries-in-Depth/2/

    0 讨论(0)
提交回复
热议问题