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