开发者

Entity-relationship modeling for x-follows-y scenario

开发者 https://www.devze.com 2023-03-27 00:10 出处:网络
Assume there are two models: User and Question. I can use @OneToMany to indicate that one user can have multiple questions. Now if I want to allow user to follow one or more questions, should I build

Assume there are two models: User and Question. I can use @OneToMany to indicate that one user can have multiple questions. Now if I want to allow user to follow one or more questions, should I build a Follow model which has two properties, user and question? Or simply add a property into User model for the list of questions followed? Which one is better? Wh开发者_开发问答at's the general design principle for this kind of scenario? Considering backend database operations, which approach above would be more efficient?


The key idea here is that a question has a single asker but multiple followers. Working at the data model, where you envision everything as tables, you would design as follows:

USER (id(PK), name, ...)
QUESTION (id(PK), title, text, author(FK to USER))
FOLLOW (userid(FK to USER), questionid (FK to QUESTION))

Because the author relation is one-to-many from USER to QUESTION and many-to-many between USER and QUESTION. The FOLLOW table is the usual join table.

Now doing the ORM with JPA is where things get interesting. Yes, you can avoid building a Follow class explicitly by storing a list of questions for each user. You will need @ManyToMany and @JoinTable. Is this more efficient than an explicit Follow class, perhaps with two @ManyToOnes or two @OneToManys? I'm not really sure, but I would suspect that since JPA is just a specification and there can be multiple implementations, that perhaps different implementations can, well, differ in how performant they are. You can of course try things both ways, write up some queries, and look at the generated SQL. If you are already aware of techniques for efficient fetch strategies, and have other skills like avoiding the n+1 select problem, then you may find this a fun exercise.

Certainly, avoiding a model class for a join table is more ORM-ish since you can just focus on the object level and not worry too much about the underlying tables. But it is good to know what goes on behind the scenes as you still need to understand how to do efficient fetching and how to avoid n+1 selects, etc.

Also, if your follow relation has attributes of its own, you may find the explicit Follow model class is a good idea.

Bottom line is a straight many-to-many without the Follow model is probably the cleanest, but choose what is most readable for you, and do some profiling if you have any doubts. I do believe that ultimately only looking at the generated SQL will tell you what you want to know, because JPA does not specify the SQL. And JPA implementations might be pretty smart, too.

0

精彩评论

暂无评论...
验证码 换一张
取 消