Search code examples
hibernatespring-data-jpahql

Count of many to many references


While creating my first spring boot application, I stumbled upon problem of counting many to many references in Tag entity.

@Entity
public class Tag {
    @Id
    @GeneratedValue
    private long id;
    private String name;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "tag_post", joinColumns = @JoinColumn(name = "tag_id"), inverseJoinColumns = @JoinColumn(name = "post_id"))
    private List<Post> posts;
    private long weight;

in spring data repository i would like to set weight equal to number of references to given Tag

@Repository
public interface TagRepository extends JpaRepository<Tag, Long> {
    @Modifying
    @Query("Update Tag t SET t.weight = ( SELECT COUNT() FROM Post p WHERE t IN p.tags )")
    // i want to make above query work
    void updateWeights();

I could simply iterate through all tags using findAll() and and set weight ony my own, but this would not be probably optimal solution.

What should I do in order to make this query work? I appreciate any advices.

(i hope my question is not gonna be deleted due to being too trivial)


Solution

  • As workarround to my problem (which was JPQL incompetence actually) i decided to just create method like this.

    @Override
    public void updateWeights()
    {
    
        for(Tag tag: tagRepository.findAll())
        {
    
            tag.setWeight(0);
            tagRepository.save(tag);
        }
    
        List<Post> posts = postRepository.findAll();
    
        for(Post post:posts)
        {
            List<Tag> tags = post.getTags();
            for(Tag tag: tags)
            {
                tag.setWeight(tag.getWeight()+1);
                tagRepository.save(tag);
            }
    
        }
    
    }