简体   繁体   中英

Spring data jpa specification for unidirectional many-to-one

public class Hotel{
    @ManyToOne(optional = false)
    @NotNull
    @JoinColumn(name = "hotel_city", referencedColumnName = "city_id")
    private City city;
}

public class City{
    @Column(name = "public_id", updatable = false, unique = true)
    @NotEmpty
    private String publicId;
}

I'd like to find all hotels which city's publicId equals to given string.

public Predicate toPredicate(Root<Hotel> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Subquery<City> subquery = query.subquery(City.class);
                Root<City> subRoot = subquery.from(City.class);
                Predicate cityIdPredicate = cb.equal(subRoot.get("publicId"), criteria.getValue().toString());

                return cb.equal(root.get("city"), cityIdPredicate);
}

I'm trying to do using code above to

  1. select city in city table which publicId is equals to given string;
  2. get hotel's city and compare it with the result of #1.

It seems something goes wrong. It's my first time using specification, any tips are helpful. Thanks.

大声笑,我只是找到了最简单的解决方案。

        return cb.equal(root.get("city").get("publicId"), criteria.getValue().toString());

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