Spring Data Jpa和规范 - ManyToMany

时间:2017-05-28 15:29:10

标签: hibernate jpa spring-boot spring-data-jpa

我遇到类似的问题:Spring Data Jpa and Specification - how to work with ManyToOne and ManyToMany relations?

我有3个表:演员,电影和按钮(电影和演员的连接表)和spring boot,hibernate-jpamodelgen

@Entity
public class Actor {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

...
}

@Entity
public class Movie implements BaseId {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
....

}

我想获得那些有两个或更多演员在一起的电影。类似这样的查询:

select * from movie 
    join mactors on movie.id = mactors.movie
    where mactors.actor = x and mactors.actor = y and ...;

public static Specification<Movie> findMoviesByActors(List<Long> actors) {
    return (root, criteriaQuery, criteriaBuilder) -> {
        ...
        return ...
    };
}

我不知道接下来会发生什么。

任何暗示都将受到赞赏。 感谢

1 个答案:

答案 0 :(得分:0)

我原来的SQL查询似乎错了。 一个有效的SQL将是:

select distinct * from movie 
    join mactors on movie.id = mactors.movie_id 
    where mactors.actor_id in (x, y, z...)
group by movie.title
having count(movie.id) >= numberOfActors;

下面的代码有效:

public static Specification<Movie> findByActorsId(List<Long> actorIds) {
    return new Specification<Movie>() {
        @Override
        public Predicate toPredicate(Root<Movie> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Join<Movie, Actor> join = root.join(Movie_.actors);

            Predicate actorIdPredicate = cb.disjunction();
            for(Long aid : actorIds) {
                actorIdPredicate.getExpressions().add(cb.equal(join.get(Actor_.id), aid));
            }

            Expression<Long> count = cb.count(root.get(Movie_.id));
            CriteriaQuery<Movie> q = (CriteriaQuery<Movie>) query.distinct(true).groupBy(root.get(Movie_.title)).
                    having(cb.greaterThanOrEqualTo(count, new Long(actorIds.size()));

            return actorIdPredicate;
        }
    };
}

我没有设法让条款工作,但我在循环中做了一个OR ......

欢迎任何改进提示:)