3

I am developing small app which works with spring-data, I need to implement search by some fields by I cannot figure out how to search by collection field values. Maybe my whole entities are wrong.

My goal is to have reserved days for offers and in search I want to find offers which are free in date range.

public class Offer {
protected List<DbDate> reservedDbDates = new ArrayList<DbDate>();}

public class DbDate {
private Offer offer;
private Date date;}

Maybe there are suggestions how to handle date field in offer?

Anyway I am trying to implement search in this way:

public class OfferSpecifications {
//http://www.zenjava.com/2012/03/20/search-like-you-mean-it/
public static Specification<Offer> searchAllOffers(final Float priceFrom, final Float priceTo, final Date dateFrom) {
    return new Specification<Offer>() {
        public Predicate toPredicate(Root offer, CriteriaQuery query, CriteriaBuilder builder) {
            Predicate predicate = builder.conjunction();
            if (priceFrom > 0) {
                predicate.getExpressions().add(builder.greaterThanOrEqualTo(offer.get("price"), priceFrom));
            }

            if (priceTo > 0) {
                predicate.getExpressions().add(builder.lessThanOrEqualTo(offer.get("price"), priceTo));
            }


            if (dateFrom != null) {
               ????
            }

            return predicate;
        }
    };
}

}

And use it in here:

offerRepository.findAll(OfferSpecifications.searchAllOffers(priceFrom, priceTo, dateFrom));

So any suggestions in this case?

Thank you!

sandris
  • 1,478
  • 2
  • 18
  • 34
  • Hi. Try something like this: criteria.where(criteriaBuilder.lessThanOrEqualTo(offer.get("date"), dateFrom)); or if jpql involded then: ..........someObject.date <= :date).setParameter("date", dateFrom, TemporalType.DATE); – legion Sep 29 '13 at 18:58
  • Well the problem is that I have list of dates in offer :| With sql I would do like: (select count(*) from DbDate date where date.offer = o and date.date >= :dateFrom) > 0 – sandris Sep 29 '13 at 19:04
  • Take a look at this http://stackoverflow.com/questions/10708809/how-to-query-for-entities-by-their-collection-value – Dimitar Pavlov Jan 08 '14 at 14:31

0 Answers0