简体   繁体   中英

Spring Data not executing query

I have an issue with query execution.

Here is my structure:

ProductPrice

@Data
@Entity
@Table(name="\"Product_price\"")
public class ProductPrice {
    @Id
    @SequenceGenerator(name="product_price_id_seq",
            sequenceName="product_price_id_seq",
            allocationSize=1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
            generator="product_price_id_seq")
    private long id;
    private Float price;
    private Date date_from;
    @ManyToOne
    private Product product;
}

Here is my ProductPriceDto

@Data
public class ProductPriceDto implements Serializable {
    public Float price;
    public Date date;
}

Here Is my PriceRepository

public interface PriceRepository extends CrudRepository<ProductPrice, Long> {
    public static final String FIND_LAST_PRICE = "SELECT p.price, MAX(p.date_from) FROM ProductPrice p WHERE p.product = ?1 GROUP BY p.product";

    @Query(FIND_LAST_PRICE)
    ProductPriceDto findPrice(@Param(value = "product") Long product);

    @Override
    List<ProductPrice> findAll();
}

Now, when I am trying to execute findPrice on PriceRepository , I am getting an error of:

java.lang.IllegalArgumentException: Parameter value [1] did not match expected type [com.eternity.model.Product (n/a)]]

What am I doing wrong?

EDIT

Despite good answers I've received from Wim, I decied to go with:

ProductPrice findFirstByProductIdOrderByDateFromDesc(@Param(value = "product") Long product);

Your query method expects a Long as the method argument, but in your JPQL query, you want a Product .

Change the query method argument to a Product .

ProductPrice model class has a Product product property, not a Long product , for this reason you have that error.

you should change your PriceRepository has below

public interface PriceRepository extends CrudRepository<ProductPrice, Long> {
    public static final String FIND_LAST_PRICE = "SELECT p.price, MAX(p.date_from) FROM ProductPrice p WHERE p.product = ?1 GROUP BY p.product";

    @Query(FIND_LAST_PRICE)
    List<ProductPrice> findPrice(@Param(value = "product") Product product);

    @Override
    List<ProductPrice> findAll();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM