• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

[JPA] Conditional entity relationship related to entity field

 
daniele licitra
Ranch Hand
Posts: 81
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi to all.
I've the entity permission with fields entity.permissionType and entity,relatedId.
If the permissionType is set to user, the relatedId point to users' table; if the permissionType is set to group, the relatedId point to groups' table.
With an entity i want to describe the permission for users and for groups.

Which notation I must use to resolve this problem?
 
Rob Spoor
Sheriff
Pie
Posts: 20750
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two possibilities:
1) Groups and users share a common super class which is also an entity. In this case, you can use that super class as the reference in the relationship. You would need to use instanceof and casting to get the proper one.

2) They don't. In this case, with regular JPA relationships, it's not directly possible what you want to do. You can create two relationships, one to user and one to group, but you have to ensure that only one is set through code. You can use entity life cycle listeners to ensure that after loading or before saving only one is set.

There is one other option: sub class permission:
You can use the Permission entity to do all your querying, but afterwards you would need to use instanceof to see if it's a user or group permission.
 
daniele licitra
Ranch Hand
Posts: 81
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you a lot! I will try solution 2
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic