如何使用Hibernate选择列?

时间:2012-05-18 12:08:01

标签: java mysql hibernate hibernate-criteria

我想使用Hibernate选择单个列而不是整个对象。到目前为止,我有这个:

 List<String> firstname = null;

 firstname = getSession().createCriteria(People.class).list();

我的问题是上面的代码将整个People表作为对象返回,而不仅仅是“firstname”。我不知道如何指定只返回“firstname”而不是整个对象。

3 个答案:

答案 0 :(得分:44)

您可以为此设置投影,如:

.setProjection(Projections.property("firstname"))

有了这个,你只能获得第一个名字。

我在堆栈上找到了另一个具有相同场景的链接。希望这也有助于How to use hibernate criteria to return only one element of an object instead the entire object?

答案 1 :(得分:7)

如果您需要查询2个或更多列并从查询中获取值,则可以使用以下方法:

....
crit.setProjection(Projections.property("firstname"));
crit.setProjection(Projections.property("lastname"));

List result = crit.list();

...

for (Iterator it = result.iterator(); it.hasNext(); ) {
    Object[] myResult = (Object[]) it.next();
    String firstname = (String) myResult[0];
    String lastname = (String) myResult[1];

    ....
}

答案 2 :(得分:2)

如果您想要条件基础投影,可以使用ProjectionList e.g

  ProjectionList prjection = Projections.projectionList();
if(abc){
    prjection.add(Projections.property("firstname"));
}
else if(xyz){
    prjection.add(Projections.property("lastname"));
}

    ........

    criteria.setProjection(prjection);
相关问题