带有count字段的JPQL ManyToMany查询

时间:2018-06-15 16:54:12

标签: java spring-boot jpa spring-security hibernate-mapping

我在具有弹簧安全性的Spring启动应用程序中的两个实体(用户和电影)之间存在多对多的关系。

我想制作一个可以查找所有电影的REST API,并包含一个新字段,用于显示已登录用户是否观看过该电影。

我找不到一种简单的方法,我只找到了一个在查询中创建新DTO对象的解决方案。我接下来会显示我的代码。

实体如下:

影:

@Entity
@Table(name = "movies")
public class Movies implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;

@NotNull
@Size(max = 100)
@Column(name = "name", length = 100, nullable = false)
private String name;

@Column(name = "jhi_year")
private Long year;

@Size(max = 100)
@Column(name = "category", length = 100)
private String category;

@ManyToMany(mappedBy = "movies")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<User> users = new HashSet<>();

用户:

@Entity
@Table(name = "user")
public class User implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;

@Size(max = 50)
@Column(name = "login", length = 50)
private String login;

@Size(max = 250)
@Column(name = "bio", length = 250)
private String bio;

@ManyToMany
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JoinTable(name = "user_movies",
           joinColumns = @JoinColumn(name="user_id", referencedColumnName="id"),
           inverseJoinColumns = @JoinColumn(name="movies_id", referencedColumnName="id"))

我所做的是一个带有JPQL @query的@Repository类,如下所示:

@Query("select new com.test.service.dto.MoviesDTO(movies.id, movies.name, movies.year, movies.category, " +
" count(users.id)) from Movies movies left join movies.users users on users.login = ?#{principal.username} group by movies.id ")
Page<MoviesDTO> findAll(Pageable pageable);

这很好用,但有更简单的方法吗?找到一个方法来实现这个在实体类中添加一个新对象是完美的,避免在查询中创建一个新的DTO对象。

我知道这与我前段时间发布的this one几乎相同,这对我来说仍然是一个谜。

很多,非常感谢!

1 个答案:

答案 0 :(得分:0)

感谢jasarez的回答。我更改了DOT进行投影,它就像一个吊饰一样!

存储库:

@Query("select movies.id as id, movies.name as name, movies.year as year, movies.category as category, count(users.id) as moviesCount " +
    "from Movies movies left join movies.users users on users.login = ?#{principal.username} group by movies.id")
     Page<MovieWithUserData> findAllWithUserData(Pageable pageable);

和投影:

public interface MovieWithUserData {

    Long getId();

    String getName();

    String getCategory();

    Integer getYear();

    Long getMoviesCount();

}