Search code examples
language-agnosticdatamodel

Best Practice: Should one avoid bi-directional relationships?


I wonder what the best practice is to deal with a data model like this: Simple security model

We have 3 entities:

  • Role
  • User
  • Permission

Note that the entities are represented as java classes and will be mapped to a database via hibernate, anyway I think the question could be answered without having knowledge of these technologies.

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

Is it ok to have a bi-directional relationship here? So, that you can ask Role to give you all his members and to ask User to give you all his roles.

It's very comfortable that you can ask both entities, however one drawback is that whenever you remove a relationship you have to manage both entities.

E.g. if you remove Role from a User you have also to remove the User from the Role. This can be quite annoying if there are many of these relationships. Therefore I would like what the best practice is.


Solution

  • I try to avoid bidirectional relationships. Instead replace one direction with an explicit query in you DAO/Repository. Keeps the model simpler and if done correctly via interfaces the application clean of circular dependencies