gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:31:54 26 4
gpt4 key购买 nike

我有三个类: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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com