我有一个简单的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
。
解决方案是什么?
答案 0 :(得分:1)
如果您无法将对象转为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