将JPA或Hibernate投影查询映射到DTO(数据传输对象) [英] Mapping JPA or Hibernate projection query to DTO (Data Transfer Object)

查看:435
本文介绍了将JPA或Hibernate投影查询映射到DTO(数据传输对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的DAO层中,我有一个像这样的Find函数

In my DAO layer, I have a Find function like this

public List<?> findCategoryWithSentenceNumber(int offset, int maxRec) {
  Criteria crit = getSession().createCriteria(Category.class, "cate");
    crit.createAlias("cate.sentences", "sent");

    crit.setProjection(Projections.projectionList().
    add(Projections.property("title"), "title").
    add(Projections.count("sent.id"), "numberOfSentence").
    add(Projections.groupProperty("title"))
  );

  crit.setFirstResult(offset);
  crit.setMaxResults(maxRec);

  return crit.list();
}

因此,为了读取数据,我必须使用Loop(带有Iterator)

So, in order to read the data, I have to use a Loop (with Iterator)

List<?> result = categoryDAO.findCategoryWithSentenceNumber(0, 10);
// List<DQCategoryDTO> dtoList = new ArrayList<>(); 

for (Iterator<?> it = result.iterator(); it.hasNext(); ) {
  Object[] myResult = (Object[]) it.next();

  String  title = (String) myResult[0];
  Long count = (Long) myResult[1];


  assertEquals("test", title); 
  assertEquals(1, count.intValue()); 

  // dQCategoryDTO = new DQCategoryDTO();
  // dQCategoryDTO.setTitle(title);
  // dQCategoryDTO.setNumberOfSentence(count);
  // dtoList.add(dQCategoryDTO);

}

我的问题是:是否有任何api框架可以轻松地将List<?> result转换为DTO对象列表(例如DQCategoryDTO),而无需使用任何循环,迭代器和调用setter/getter来填充值?

My question is: is there any api, framework to easily convert the List<?> result in to a list of DTO object (say, DQCategoryDTO) without using any loop, iterator and calling setter/getter to fill the value?

推荐答案

您可以使用此处中参考Hibernate文档.在第13.1.5节

You can use ResultTransformer which can convert from alias to bean (DTO) properties. For usage you can refer to the Hibernate docs here at section 13.1.5

这篇关于将JPA或Hibernate投影查询映射到DTO(数据传输对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆