java 如何使用jpa和多对多关系通过至少一个公共标签获取所有用户

mxg2im7a  于 2023-01-24  发布在  Java
关注(0)|答案(1)|浏览(104)

我想找到所有使用JPA、spring Boot 以及用户和标签之间多对多关系的至少有一个公共标签的用户。

@Entity
@Table(name = "user", schema = "public")
public class User {

    @Id
    @GeneratedValue
    private Long id;
  

    @ManyToMany(fetch = FetchType.LAZY,
            cascade = {
                    CascadeType.ALL
            })
    @JoinTable(name = "user_tags",
            joinColumns = {@JoinColumn(name = "user_id")},
            inverseJoinColumns = {@JoinColumn(name = "tag_id")})
    private List<Tag> tags = new ArrayList<>();
//..constructor etc...

此标记表:

@Entity
@Table(name = "tag", schema = "public")
public class Tag {
    @Id
    @GeneratedValue
    private Long id;
    private String descriptor;
    @JsonBackReference
    @ManyToMany(fetch = FetchType.LAZY,
            cascade = {
                    CascadeType.ALL
            },
            mappedBy = "tags")
    private List<User> users = new ArrayList<>();
//..constructor etc...

这是我的用户存储库

@Query("SELECT u FROM Tag t  JOIN t.users tid INNER JOIN User u on(u.id = tid.id) WHERE 
t.descriptor IN :tagList")
List<User> findUserByCommonTags(@Param("tagList") List<String> tagList);

我知道问题出在用户库的SQL查询上。有帮助吗?

uklbhaso

uklbhaso1#

可能是这样的:

SELECT u FROM Users u 
JOIN Tag t 
WHERE t IN (
    SELECT t1 FROM Tag t1
    JOIN User u1 
    WHERE t1.description IN ( :tagList )
    GROUP BY t1 HAVING( COUNT(DISTINCT u1) > 1 )
) 
;

相关问题