【问题标题】:Is it possible to call a native query and store the result set in a non-entity object?是否可以调用本机查询并将结果集存储在非实体对象中?
【发布时间】:2026-01-26 16:00:01
【问题描述】:

我正在尝试使用本机查询获取非实体对象,我想将其用作应用程序中某个页面上的视图模型。 我正在关注this 的解释,它没有详细说明,对于已经熟悉该主题并且只需要提醒的人来说,它更像是一个备忘单。 很久以前就有类似的问题herehere,因为我不知道所提供的代码块应该去哪里,所以我想我可能会问一个新问题。 无论我尝试什么,我都会得到这个异常:

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type

这是我的模型类:

public class ProductForHomeView {

    private int id;
    private String title;
    private EProductType productType;
    private double price;
    private int quantity;

    public ProductForHomeView(int id, String title, EProductType productType, double price, int quantity) {
        this.id = id;
        this.title = title;
        this.productType = productType;
        this.price = price;
        this.quantity = quantity;
    }

存储库界面:

public interface IProductsRepository extends CrudRepository<Products, Integer> {
    @Query(value = "SELECT products.id, products.title, products.the_type AS productType, stock.price, stock.quantity FROM products LEFT JOIN stock on products.id=stock.product_id", nativeQuery = true)
    List<ProductForHomeView> getProductsInfoForTheHomePage();   
}

我尝试映射非实体类的实体类之一:

@Entity
@Table(name = "stock")
@SqlResultSetMapping(
        name="ProductForHomeViewMapping",
        classes={
        @ConstructorResult(
        targetClass=qualified.name.ProductForHomeView.class,
        columns={
        @ColumnResult(name="id", type=Integer.class),
        @ColumnResult(name="title", type=String.class),
        @ColumnResult(name="productType", type=EProductType.class),
        @ColumnResult(name="price", type=Long.class),
        @ColumnResult(name="quantity", type=String.class)
        })})
public class Stock {
// mapped fields, constructors, geters and setters...
}

感谢您的任何意见!

【问题讨论】:

    标签: java spring hibernate jpa


    【解决方案1】:

    我使用@SqlResultSetMapping@NamedNativeQuery

    使用以下方法更改您的 Curd 存储库方法

    public interface IProductsRepository extends CrudRepository<Products, Integer> {
        @NamedNativeQuery(value = "SELECT products.id, products.title, products.the_type AS productType, stock.price, stock.quantity FROM products LEFT JOIN stock on products.id=stock.product_id", resultSetMapping = "ProductForHomeViewMapping")
        List<ProductForHomeView> getProductsInfoForTheHomePage();   
    }
    

    更多信息可here

    【讨论】:

    • 你确定我们可以在这样的方法声明上使用注解@NamedNativeQuery吗?
    • 我第二个问题,因为我没有找到可以像这样注释方法声明的来源。提供的链接信息量很大,但没有提供关于“如何将本机查询映射到非实体对象?”问题的答案
    【解决方案2】:

    【讨论】:

    • 谢谢!其实你提供的链接帮我解决了这个问题!
    最近更新 更多