我正在寻找将一个表中的多行映射到单个实体的最佳方法。我的数据库表如下所示:
principal_id permission target
12312313 PERM1 1000
12312313 PERM2 1000
12312313 PERM2 1002
理想情况下,我想将此表的内容映射到我的Principal @Entity作为字段,如下所示:
@Entity
...
public class Principal {
@Id
private long principalId;
...
private Map<String, List<Long>> permissionMap;
}
最好的方法是什么?
答案 0 :(得分:3)
我不知道如何做到你想要的。我能得到的最接近的是:
@Embeddable
public class Permission {
private String permission;
private int target;
}
@ElementCollection
@CollectionTable(name="foo", joinColumns = @JoinColumn(name = "principal_id"))
private Set<Permission> permissions;
如果每个目标只有一个权限,那么您可以使用地图:
@ElementCollection
@CollectionTable(name="foo", joinColumns = @JoinColumn(name = "principal_id"))
@MapKeyColumn(name="permission")
@Column(name="target")
private Map<String, Integer> permissions;
可悲的是,我认为没有办法为包含馆藏的地图做到这一点。
答案 1 :(得分:-1)
我建议采用以下结构:
@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 **/
}
}