JPA one to many map key
I have开发者_如何学运维 the following
@OneToMany(mappedBy="role")
@MapKey(name="role.name")
private Map<String,UserRole> userRoles = new HashMap<String,UserRole>();
I want to use the name attribute of Role object in UserRole as the key for the Map, How can i achieve this. @MapKey(name="role.name") does not work.
My UserRole.java has the following
@ManyToOne
@JoinColumn(name="roleId")
private Role role;
In JPA the @MapKey can only be a local field. You could try to use just "role" as the key, as it should be similar to using the role name. Or, map the role name into the UserRole. You could also just map it as a List or Set and just define methods in your class to access it by the key.
If you are using EclipseLink you can also use a method as the map key, so you could define a getRoleName() in UserRole that returns the Role's name, and use this with the @MapKey.
I am shooting in the dark :)
If you want to use the name attribute of Role object in UserRole as the key for the Map. you can try to make the name attribute in Role object as @Id. Then your @MapKey(name="role")
Hope this help. we can discuss more if this won help. I also try to understand this kind of stuff now.
精彩评论