java - 如何将 native 查询结果映射到自定义类对象?

标签 java hibernate jpa nativequery

我有三个类:Lending、LendingReturn 和 ProductLending。

贷款

@Entity
public class Lending implements Serializable {

@Id
private Long id;

private BigDecimal amount;

private Instant createdDate;

private User lender;

private ProductLending productLending;

}

借贷返回

@Entity
public class LendingReturn implements Serializable {

@Id
private Long id;

private BigDecimal amount;

private Instant createdDate;
}

产品借用

@Entity
public class ProductLending implements Serializable {

    @Id
    private Long id;

    private String title;
}

下面是我的 native 查询。我想查询然后将结果映射到良好的映射列表

Query query = em.createNativeQuery("select l.id, pl.title, sum(lr.amount)+l.amount as total_return, " +
                                            "(select amount as yesterday_return from lending_return where lending_id=l.id and date(created_date)=current_date-2), " +
                                            "l.period_in_day-(current_date-date(l.created_date)) as mature_in_day " +
                                            "from lending_return lr right join lending l on lr.lending_id=l.id " +
                                        "join product_lending pl on l.product_lending_id=pl.id " +
                                        "where l.lender_id=:lenderId " +
                                        "group by l.id, pl.title, l.amount");

    query.setParameter("lenderId", userService.getLoggedInUser().getId());
    List<Object[]> resultList = query.getResultList();

因此查询返回列:id、title、total_return、today_return

然后结果列表包含:

[
  [
    2804,
    "Title 1",
    1001800,
    600,
    24
  ],
  [
    2809,
    "Title 2",
    null,
    null,
    28
  ]
]

如何映射 resultList 以使结果如下所示?

[
  {
    "id": 2804,
    "title": "Title 1",
    "total_return": 1001800,
    "yesterday_return": 600,
    "mature_in_day": 24
  },
  {
    "id": 2809,
    "title": "Title 2",
    "total_return": null,
    "yesterday_return": null,
    "mature_in_day": 28
  }
]

最佳答案

您需要手动映射它:

public String map(ResultSet rs) throws Exception {
        Lending lend = new Lending ();
            lend.setId( rs.getLong("id"));
        // complete all columns 
        return lend;
    }

并在需要的地方调用该方法。

关于java - 如何将 native 查询结果映射到自定义类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59252535/

相关文章:

java - 为什么 Spring 的事务管理不适用于此配置?

java - 如何保留父实体而不更新具有多对多关系的子实体?

Java HttpURLConnection 命令通过命令行完美运行,但不能通过 Web UI

java - 如何在JTable的某一列中设置图标?

mysql - EJBQL/HQL 命名参数列表

java数据库对象级安全性

java - JPA - 加载实体的一对多关系时出现 MySQL 语法错误

java - 双向映射情况下如何在 spring-data-jpa 中删除

java - Webview 占据整个屏幕

java - 如何在 Spark 中打印 DataFrame 列的唯一值?