JPA中的日期比较和最大值

时间:2018-05-25 17:58:32

标签: java jpa java-ee

我想问两个关于JPA的问题: 我的查询(Offer.findHighestOffer)有什么问题,它应该从与拍卖相关的每个报价中选择最高价格,是否写得正确?

@Entity
@NamedQuery(name = "Offer.findAll", query = "SELECT o FROM Offer o")
@NamedQueries({
        @NamedQuery(name = "Offer.findById", query = "SELECT o FROM Offer o WHERE o.id = ?1"),
        @NamedQuery(name = "Offer.findHighestOffer", query = "SELECT o FROM Offer o WHERE o.auction.id = ?1 HAVING MAX(o.price)")
})
public class Offer implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private double price;
    @ManyToOne
    private Auction auction;
    @ManyToOne
    private UserAccount user;
    private Timestamp creationDate = new Timestamp(System.currentTimeMillis());

并且有人可以告诉我如何比较jpql中的时间戳字段吗?

这是我的拍卖实体

@Entity

@NamedQueries({
        @NamedQuery(name = "Auction.findById", query = "SELECT a FROM Auction a WHERE a.id = ?1"),
        @NamedQuery(name = "Auction.findAll", query = "SELECT a FROM Auction a"),
        @NamedQuery(name = "Auction.findExpired", query = "SELECT a FROM Auction a WHERE a.expireDate < ?1"),
})
public class Auction implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @ManyToOne
    private UserAccount user; //nie daje sie id tylko obiekt
    private String description;
    private String title;
    private double price;
    @OneToMany(mappedBy = "auction", orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Offer> offers = new LinkedList<Offer>();
     private Timestamp creationDate = new Timestamp(System.currentTimeMillis());
     private Timestamp expirationDate;

我已经阅读了一些关于将当前时间作为参数传递的内容,我这样做但它仍然崩溃

Problem compiling [SELECT a FROM Auction a WHERE a.expireDate < ?1]. 
[30, 42] The state field path 'a.expireDate' cannot be resolved to a valid type.

在我的代码中,它的用法如下:

Offer highestOffer;
TypedQuery<Auction> auctionQuery = em.createNamedQuery("Auction.findExpired", Auction.class);
auctionQuery.setParameter(1, new Timestamp(System.currentTimeMillis()), TemporalType.TIMESTAMP);

1 个答案:

答案 0 :(得分:0)

您可以按以下方式替换查询。

  @NamedQueries({
            @NamedQuery(name = "Auction.findById", query = "SELECT a FROM Auction a WHERE a.id = :id")
            @NamedQuery(name = "Auction.findExpired", query = "SELECT a FROM Auction a WHERE a.expireDate < :expireDate")

并设置参数

 TypedQuery<Auction> auctionQuery = em.createNamedQuery("Auction.findExpired", Auction.class);
    auctionQuery.setParameter("expireDate", new Timestamp(System.currentTimeMillis()), TemporalType.TIMESTAMP);