JPA polymorphic oneToMany

后端 未结 4 2098
栀梦
栀梦 2020-12-19 11:44

I couldn\'t figure out how to cleanly do a tag cloud with JPA where each db entity can have many tags.

E.g

Post can have 0 or more Tags User can have 0 or mo

4条回答
  •  执念已碎
    2020-12-19 12:33

    If you don't need polymorphic queries such as "get everything tagged tagged Foo", then you can also introduce a new entity (say TaggingTarget), and create a unidirectional one-to-one relation from User (Post, etc) to TaggingTarget and many-to-many relation between TaggingTarget and Tag:

    @Entity
    public class User {
        @OneToOne
        private TaggingTarget target;
        ...
    }
    
    @Entity
    public class TaggingTarget {
        @ManyToMany(...)
        private Set tags;
        ...
    }
    
    @Entity
    public class Tag {
        @ManyToMany(...)
        private Set targets;
        ...
    }
    

    The difference from Affe's solution is that you don't need a tag.getTaggedUsers(), tag.getTaggedPosts(), etc and can add new tagged entities without changing Tag. Tagged entities can be queried using JPQL:

    select u from User u where :tag member of u.target.tags
    

    or

    select u from User u join u.target.tags t where t.name = :name 
    

提交回复
热议问题