【问题标题】:How do you select a column using Hibernate?如何使用 Hibernate 选择列?
【发布时间】:2012-05-26 00:17:14
【问题描述】:

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

 List<String> firstname = null;

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

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

【问题讨论】:

    标签: java mysql hibernate hibernate-criteria


    【解决方案1】:

    如果你想要条件基础投影,你可以使用 ProjectionList 例如

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

    【讨论】:

      【解决方案2】:

      如果您需要查询 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];
      
          ....
      }
      

      【讨论】:

        【解决方案3】:

        你可以像这样设置投影:

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

        这样你只能得到名字作为回报。

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

        【讨论】:

          猜你喜欢
          • 2013-05-10
          • 2011-10-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多