LunaticJape
LunaticJape

Reputation: 1584

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.

Upvotes: 6

Views: 4384

Answers (1)

LunaticJape
LunaticJape

Reputation: 1584

LOL, I just found the simplest solution.

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

Upvotes: 11

Related Questions