Hibernate createQuery resultset Mapping(Spring启动)

时间:2017-08-24 11:32:48

标签: java hibernate spring-boot

我正在解雇HQL加入查询

@Override
public List<Object> getCourseIdWithStatus(int courseId, String status) {

    String queryString = "select sc.courseId, sc.name, sct.streamId from Course "
            + "sc join CoursesTypeInformation sct ON(sc.courseId = sct.courseId)"
            + " where sc.courseId = ?1 and sc.status = ?2 and sct.status = ?3";
    Query query = entityManager.createQuery(queryString);
    query.setParameter(1, courseId);
    query.setParameter(2, status);
    query.setParameter(3, status);
    return (List<Object>)query.getResultList();
}

这是 HQL查询而非本机SQL

现在我有一个pojo类

public class BasicData {

    private int courseId;

    private String name;

    private int streamId;

    .. setters and getters

}

我想将查询结果映射到POJO。我应该使用什么?

1 个答案:

答案 0 :(得分:0)

有很多方法可以实现这一点,其中之一是在POJO类中创建构造函数 这里有一些来自我的代码的例子:

POJO:

@Entity
@Table(name="TBL_KCT_SPL_STOCK_DTL")
public class TblKctSplStockDtl implements Serializable{
   ...
   public TblKctSplStockDtl(String reclaim, BigDecimal){ 
    this.reclaim = reclaim;
    this.tonnage = tonnage;
   }
  ...
} 

HQL:

String hql = "select new TblKctSplStockDtl(t.reclaim, sum(t.tonnage)) from TblKctSplStockDtl t "
            + "where t.idStock = :idStock and t.state = 'IN' "
            + "group by t.reclaim ";

Query q = sessionFactory.getCurrentSession().createQuery(hql);