简体   繁体   中英

Hibernate criteria and/or with many-to-many

This is the query i'm running:

    List<Coupon> coupons = getDb().createCriteria(Coupon.class)
    .add(Restrictions.le("validFrom", startTime.getTime()))
    .add(Restrictions.ge("validUntil", startTime.getTime()))
    .add(Restrictions.eq("user", user))
    .createAlias("spots", "spotsAlias")
    .add(Restrictions.or(
            Restrictions.eq("isGlobal", true),
            Restrictions.eq("spotsAlias.id", spot.getId())
            ))
    .add(Restrictions.eq("isRedeemed", false))
    .add(Restrictions.eq("isDeleted", false))
    .add(Restrictions.eq("isActive", true))
    .addOrder(Order.asc("isGlobal"))
    .addOrder(Order.desc("validFrom"))
    .list();

it's supposed to get all coupons that are:

  • valid at startTime
  • related to user
  • global or related to a specific spot
  • not redeemed
  • not deleted
  • activated

the coupons are in many-to-many relationship with spots. the relationship works - this query does return coupons that are specifically related to the queried spot. Unfortunately, it never returns global coupons, even when there are no "local" coupons in the database at all.

Any suggestions? help will be very much appreciated!

Try using disjunction and see:

 .add( Restrictions.disjunction().add(Restrictions.eq("global", Boolean.TRUE))
                              .add(Restrictions.eq("spotsAlias.id", spot.getId())))

Also if global is a property in your Entity, then you need to use :

Restrictions.eq("global", Boolean.TRUE)

Also if you refer to Restrictions class, it has only

eq(String propertyName, Object value) 

method which takes object as second parameter and not a primitive type.

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