2017-05-28 96 views
0

我有一個類似的問題與這一個:Spring Data Jpa and Specification - how to work with ManyToOne and ManyToMany relations?春數據JPA和規範 - 多對多

我有3個表:演員,電影和mactors(連接表爲電影和演員)彈簧開機,休眠,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; 
.... 

}

我想獲得其中2級或更多的行動者已經在了一起那些電影。類似這樣的查詢:

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 ... 
    }; 
} 

我不知道接下來會發生什麼。

任何提示,將不勝感激。 謝謝

回答

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; 
     } 
    }; 
} 

我沒條款去上班,但我做了一個或循環...

歡迎提出任何提示:)