mysql - Hibernate allow foreign key to be one of many classes? -
i'm trying implement hashtag functionality in database, allowing me assign hashtag different classes. possible have foreign key inside tags class, 1 of many different classes (article, video, image)? mean having discriminator column.
e.g
@entity @table(name="tags") public class tags { private string tagname; // hashtag name; e.g cool-photo private <article, video, photo> relatedobject; private string type; // can either article, video, photo } in example i'd able run simple query:
select t.* tags t type = 'article' , tagname = 'tag-searching-for' inner join article on t.relatedobject = a.articleid; this return bunch of <type-requested> objects type requested (in case, articles)!
is there built in way of doing hibernate or have build own solution (which im happy do, i'd rather check see if theres concret 1 first).
there 2 ways, can use super entity - inheritance.
create
taggable, new super entity article, video, ...@entity public class tag { private string tagname; // hashtag name; e.g cool-photo @manytomany @jointable(...) private set<taggable> relatedobjects = new linkedhashset<>(); } @entity @inheritance(...) public abstract class taggable { @manytomany(mappedby = "relatedobjects") protected set<tag> tags = new linkedhashset<>(); } @entity public class article extends taggable { ... }make
tagsuper entity@entity @inheritance(...) public abstract class tag { protected string tagname; // hashtag name; e.g cool-photo } @entity public class articletag extends tag { @manytomany(mappedby = "tags") private set<article> articles = new linkedhashset<>(); } @entity public class article { @manytomany @jointable(...) private set<articletag> tags = new linkedhashset<>(); }
in both cases query use more (conversely 1 brought in example) [jpql style - not sql!]:
select article join a.tags t t.tagname = 'tag-searching-for' to articles specific tagname.
imho first 1 requires less refactoring , less boilerplate code, but, due java single-class inheritance limitation, cause problem if/when you'll extend model in future.
as side note, don't see meaning in using single relatedobject, changed set<>
Comments
Post a Comment