gpt4 book ai didi

java - POJO 中的 SqlResultSetMapping

转载 作者:行者123 更新时间:2023-11-30 10:39:33 25 4
gpt4 key购买 nike

我有一个简单的 POJO:

我正在尝试将标题列映射到标题字段:

@SqlResultSetMapping(
name = "ownerSaleMapping",
classes = {
@ConstructorResult(
targetClass = OwnerSale.class,
columns = {
@ColumnResult(name = "title", type = String.class)
}
)
}
)

@NamedNativeQuery(name = "ownerSaleReport", query = "SELECT title FROM content where id=:contentId", resultSetMapping = "ownerSaleMapping")
public class OwnerSale {

public OwnerSale() {
}

private String title;

public OwnerSale(String title) {
this.title = title;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}
}

我的存储库界面:

public interface OwnerSaleRepository extends JpaRepository<OwnerSale, Long> {

List<OwnerSale> ownerSaleReport(@Param("contentId") Long ownerId);
}

但是当我使用它时:

List<OwnerSale> sales = ownerSaleRepository.ownerSaleReport(6);

我遇到了这个错误:

IllegalArgumentException: Not an managed type: class domain.owner.OwnerSale

但我需要 OwnerSale 是一个 POJO 而不是 Entity

解决方案是什么?

最佳答案

如果您不能将您的对象转换为 Entity,那么使用 JdbcTemplate 和简单的 RowMapper 可能更容易?

private JdbcTemplate jdbcTemplate; //it depends on your config how to get it here.

List<OwnerSale> ownerSaleReport(Long ownerId){
String sql = "SELECT title FROM content where id=:contentId"
return jdbcTemplate.query(StringUtils.replaceEach(sql,
new String[]{":contentId"},
new String[]{ownerId.toString()}),
(rs, i) -> {
OwnerSale ownerSale = new OwnerSale();
ownerSale.setTitle(rs.getString("title"));//(or using constructor)
return ownerSale;
});
}

这里我使用 Apache 的 StringUtils 但你可以使用任何其他方式将 args 传递给 String

关于java - POJO 中的 SqlResultSetMapping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39244110/

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