0

对不起凌乱的 SQL 查询。

我有这个数据结构

@Entity
public class Stock {

//Composite PK?
@Id
@NotNull
private String id;
@NotNull
private String product_id;
@NotNull
private Integer quantity;
@NotNull
private LocalDateTime timestamp;

public class ProductSold {

    private String productId;
    private Integer itemsSold;

这两个类都具有适当的构造函数。

我有股票的相应存储库

public interface StockRepository extends JpaRepository<Stock, String> {

我正在尝试做的是一个棘手的 SQL 查询(评论更容易可视化查询),它应该返回一个 ProductSold 列表而不是 Stock

 /*
SELECT (t1.quantity - t2.quantity) as itemsSold, t1.product_id as pd
FROM stock t1 CROSS JOIN
 stock t2
WHERE MONTH(t1.timestamp) = 8 AND DAY(t1.timestamp) = 26
AND MONTH(t2.timestamp) = 8 AND DAY(t2.timestamp) = 27
AND t1.product_id = t2.product_id
ORDER BY itemsSold DESC
LIMIT 3;
 */

//Not working, not too sure why, says it can't find column quantity. In my view it should be working since it's a valid SQL Query.
@Query(value = "SELECT  new com.stock.stock.model.ProductSold(t1.product_id as productId, (t1.quantity - t2.quantity) as itemsSold )" +
        "    FROM Stock t1 CROSS JOIN Stock t2" +
        "    WHERE MONTH(t1.timestamp) = ?1 AND DAY(t1.timestamp) = ?2" +
        "    AND MONTH(t2.timestamp) = ?3 AND DAY(t2.timestamp) = ?4" +
        "    AND t1.product_id = t2.product_id" +
        "    ORDER BY itemsSold DESC" +
        "    LIMIT 3", nativeQuery = true)
List<ProductSold> findItemsSoldByTimestamp(int month1, int day1, int month2, int day2);

但我得到了这个:

org.h2.jdbc.JdbcSQLSyntaxErrorException:SQL 语句中的语法错误“SELECT NEW COM.[*]STOCK.STOCK.MODEL.PRODUCTSOLD(T1.PRODUCT_ID AS PRODUCTID, (T1.QUANTITY - T2.QUANTITY) AS ITEMSSOLD) ... .

知道有什么问题吗?我试过不在 SQL 表达式中构造,但我得到一个 ConverterNotFoundException

4

1 回答 1

0

您正在使用仅在 JPQL 中可用的构造函数表达式,但您还将查询标记为本机,即它不是 SQL。

于 2019-10-15T07:26:14.300 回答