使用左连接的JPA查询和"不存在"

时间:2017-11-25 00:01:11

标签: jpa toplink

我正在使用TopLink编写JPA查询,该查询涉及以下三个实体。

  gzsuppl = Chem.ForwardSDMolSupplier(gzip.open(infile))
  for m in gzsuppl:
  if m is None: continue
...etc

file.close()
print(count)

我需要找到所有要约用户没有优惠券的优惠或者用户的所有优惠券都是在一天前发出的。 我已经尝试了很多不同的方法,到目前为止我唯一提出的查询是,在部署时不会使服务器崩溃:

@Entity
@Table(name = "OFFERS")
public class Offers implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO, generator="offers_seq_gen")
    @SequenceGenerator(name="offers_seq_gen", sequenceName="OFFERS_SEQ")
    @Basic(optional = false)
    @Column(name = "OFFERID")
    private Long offerid;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "offers", fetch = FetchType.LAZY)
    private List<Coupons> couponsList;
}

@Entity
@Table(name = "COUPONS")
public class Coupons implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO, generator="coupons_seq_gen")
    @SequenceGenerator(name="coupons_seq_gen", sequenceName="COUPONS_SEQ")
    @Basic(optional = false)
    @Column(name = "COUPONID")
    private Long couponid;

    @Basic(optional = false)
    @Column(name = "ISSUED", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    @Temporal(TemporalType.TIMESTAMP)
    private Date issued;

    @JoinColumn(name = "USERID", referencedColumnName = "USERID")
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    private Users users;

    @JoinColumn(name = "OFFERID", referencedColumnName = "OFFERID")
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    private Offers offers;

@Entity
@Table(name = "USERS")
public class Users implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO, generator="users_seq_gen")
    @SequenceGenerator(name="users_seq_gen", sequenceName="USERS_SEQ")
    @Basic(optional = false)
    @Column(name = "USERID")
    private Long userid;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "users", fetch = FetchType.LAZY)
    private List<Coupons> couponsList;

但是,当优惠券条目不存在时,它不会返回优惠。

1 个答案:

答案 0 :(得分:0)

我设法找到了一个有效的查询。如果有人有类似的问题,请留在这里作为参考:

SELECT o FROM Offers o WHERE 
    NOT EXISTS 
        (SELECT c FROM Coupons c WHERE c.users.userid = :userid 
             AND c.issued > :yesterday AND c.offers = o) 
    OR NOT EXISTS 
        (SELECT c1 FROM Coupons c1 WHERE c1.offers = o 
             AND c1.users.userid = :userid)