Home Ask Login Register

Developers Planet

Your answer is one click away!

Radek Postołowicz February 2016

ManyToMany mapping to include some extra records

Let's say I have following model:

public class User {


    private Set<Permission> allowedPermissions;



public class Permission {


    private boolean isDefault;



Is it possible to map User.allowedPermissions so that it contains both Permissions that are connected to the User and also these with isDefault = true but are not explicitly connected?

I use Hibernate as Jpa provider.


Paolof76 February 2016

Well it would not be possible because you don't have enough information about Permissions in the User.

If you think at a many-to-many relationship, on the database it's a relation table between two other tables.

Now, in your User entity you're correctly using a Set to see all the relations stored in this cross table (let's say user_permission). But at this level you're not able to know the default permissions, that can be retrieved via a PermissionDAO very easily (I assume you're using a DAO/Service design, if not adjust it to your needs).

If you want a superset (allowedPermissions + defaultPermissions), then you can maybe write a utility method at service layer if you like:

getAllPermissions(User user) {
   return userDAO.getAllowedPermissions(user).addAll(permissionDAO.getDefaultPermissions()); 

Why at service layer? Because you need two DAOs at the same time, and you don't want to inject a DAO into another. Let me know if this is useful.

Post Status

Asked in February 2016
Viewed 1,359 times
Voted 9
Answered 1 times


Leave an answer

Quote of the day: live life