Best practice: should bi-directional relationships be avoided?

Interestingly, it is best to deal with such a data model: Simple security model

We have 3 objects:

  • Role
  • User
  • Resolution

Please note that entities are represented as java classes and will be displayed in the database through sleep mode. In any case, I think this question can be answered without knowledge of these technologies.

There is a many-to-many relationship between Role and User , and between Role and Permission .

Is it possible to have bidirectional communication here? So, you can ask Role to give you all its members and ask User give you all its roles.

It is very convenient that you can specify both objects, however, one of the drawbacks is that whenever you delete relations, you must manage both objects.

eg. if you remove Role from User , you must also remove User from Role . This can be very unpleasant if there are many such relationships. Therefore, I would like the best practice to be.

+4
source share
2 answers

I try to avoid bidirectional relationships. Instead, replace one direction with an explicit request in the DAO / Repository. Keeps the model simpler and, if everything is done correctly through the interfaces, the application cleans of circular dependencies

+4
source

Is it possible to have bidirectional communication here? So, you can ask the Role to give you all its members and ask the User to provide you with all its roles.

Yes. If you really need shipping in both directions, then there is no reason that you could not get it in the easiest way.

One of the drawbacks is that whenever you delete relationships, you have to manage both objects.

It depends on the implementation, you can implement the data model in such a way as to synchronize both ends.

+1
source

Source: https://habr.com/ru/post/1387372/


All Articles