使用Hibernate获取具有最大id值的实体

时间:2016-01-12 09:11:30

标签: java sql database hibernate orm

我想获取giftManagement.point_To的最大值,该值来自另一个表。但它不是从表中选择数据。

@Id
    @SequenceGenerator(name = "seq_offer_gen", sequenceName = "seq_offer")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_offer_gen")
    private long id;

    @ManyToOne
    @JoinColumn(name = "customer_id", nullable = false)
    private Customer customer;

    @ManyToOne
    @JoinColumn(name = "gift_management_id", nullable = false)
    private GiftManagement giftManagement;

    @Column(name = "sms_delivery_status", nullable = false)
    private String smsDeliveryStatus;

    @Column(name = "offer_received_status", nullable = false)
    private String offerReceivedStatus;






 Offer offer = (Offer) session.createQuery("FROM Offer where customer.id =:customerId and max(giftManagement.point_To)")
                    .setParameter("customerId", id)
                    .uniqueResult();

1 个答案:

答案 0 :(得分:3)

试试这样:

Offer offer = (Offer) session.createQuery(
    "select o " +
    "from Offer o " +
    "where o.id = ( select max(g.point_To) from Offer o1 join o1.giftManagement g where o1.customer.id =:customerId ) ")
.setParameter("customerId", id)
.uniqueResult();