我有三个表,每个表都映射到其中一个实体。 “已分配”表充当“用户”和“角色”之间的关系,每个表都有一个外键。我如何在我的实体上映射它,以便我可以从UserEntity获取一组EntityRoles?我无法弄清楚如何使这项工作。这甚至可能吗?
@Entity
@Table(name = "users")
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="user_id")
private long id;
@Column(name="user_username")
private String username;
@Column(name="user_password")
private String password;
@Column(name="user_email")
private String email;
//I want to be able to get a set of RoleEntities
@OneToMany(fetch = FetchType.LAZY, mappedBy = "id")
private Set<RoleEntity> roles;
}
@Entity
@Table(name = "assigned")
public class AssignedEntity implements Serializable {
@Id
//@Column(name = "assigned_role")
@ManyToOne(targetEntity = RoleEntity.class, fetch = FetchType.LAZY)
@JoinColumn(name = "fk_role")
private long roleId;
@Id
//@Column(name = "assigned_user")
@ManyToOne(targetEntity = UserEntity.class, fetch = FetchType.LAZY)
@JoinColumn(name = "fk_user")
private long userId;
}
@Entity
@Table(name = "roles")
public class RoleEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="role_id")
@OneToOne(fetch = FetchType.LAZY, mappedBy="roleId")
private long id;
@Column(name="role_name")
private String name;
}
答案 0 :(得分:1)
您使用的是不正确/不方便的映射。始终尽可能简单地保持事物。
var g = svg.select("g").attr("transform", "translate(" + window.innerWidth/2 + "," + (window.innerHeight)/2 + ")scale(" + scale + ")translate(" + -placePositionX + "," + -placePositionY + ")");
持久性提供程序将为您创建(有效)连接表。您可以使用@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue
private Long id;
@ManyToMany(fetch = FetchType.LAZY)
private List<Role> roles;
}
@Entity
@Table(name = "roles")
public class Role {
@Id
private Long id;
@Column
private String name;
}
注释指定连接表的名称。此外,您还需要考虑@JoinTable
实体的id
的自动生成值:Role
表类似于参考数据表。因此,您可能需要对roles
值进行硬编码。
获取用户角色(在持久化上下文中):
id