Reputation: 415
I am looking for the best way to map multiple rows in one table into a single entity. The database table I have is shown below:
principal_id permission target
12312313 PERM1 1000
12312313 PERM2 1000
12312313 PERM2 1002
Ideally I would like to map the contents of this table into my Principal @Entity as a field as follows:
@Entity
...
public class Principal {
@Id
private long principalId;
...
private Map<String, List<Long>> permissionMap;
}
What is the best way to do so?
Upvotes: 3
Views: 2124
Reputation: 47163
I don't know of a way to do exactly what you want. The closest i can get is:
@Embeddable
public class Permission {
private String permission;
private int target;
}
@ElementCollection
@CollectionTable(name="foo", joinColumns = @JoinColumn(name = "principal_id"))
private Set<Permission> permissions;
If you only had one permission per target, then you could use a map:
@ElementCollection
@CollectionTable(name="foo", joinColumns = @JoinColumn(name = "principal_id"))
@MapKeyColumn(name="permission")
@Column(name="target")
private Map<String, Integer> permissions;
Sadly, i don't think there's a way to do this for a map containing collections.
Upvotes: 3
Reputation: 595
I would suggest the following structure:
@Entity
...
public class Principal {
@Id
private long principalId;
/** Other properties **/
@OneToMany
private Set<Permission> permissions;
....
}
@Entity
@IdClass(PermissionId.class)
public class Permission {
@Id
private String permission;
@Id
private Long target
public static class PermissionId implements Serializable {
private String permission;
private Long target;
/** setters/getters hashcode and equals goes here **/
}
}
Upvotes: -1