【问题标题】:Map NativeQuery to POJO将 NativeQuery 映射到 POJO
【发布时间】:2019-09-03 08:49:28
【问题描述】:

我有一个 NativeQuery,我想将它映射到 POJO。

我尝试了以下方法,但它以无限循环结束。

public synchronized List<FreeIP> getFirstFreeHost() {
    String q = "SELECT i.subnet, h.ip_host FROM ip_addresses i join hosts h on i.id = h.ip_addresses_id ORDER BY i.subnet, h.ip_host";
    this.entityManager = this.entityManagerFactory.createEntityManager();
    Query query = this.entityManager.createNativeQuery(q);
    List<Object[]> rows = query.getResultList();
    List<FreeIP> result = new ArrayList<>();
    for (Object[] row : rows) {
        result.add(new FreeIP((String) row[0], (String) row[1]));
    }

    return result;
}

【问题讨论】:

    标签: java jpa nativequery


    【解决方案1】:

    看看 QLRM:https://github.com/simasch/qlrm

    那么你可以这样做:

    JpaResultMapper jpaResultMapper = new JpaResultMapper();
    
    Query q = em.createNativeQuery("SELECT i.subnet, h.ip_host FROM ip_addresses i join hosts h on i.id = h.ip_addresses_id ORDER BY i.subnet, h.ip_host");
    
    List<EmployeeTO> list = jpaResultMapper.list(q, FreeIP.class);
    

    确保 FreeIP 有一个构造函数,该构造函数接受查询的所有参数。

    【讨论】:

      猜你喜欢
      • 2014-10-01
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多