我正在研究简单的Spring安全演示,并希望将用户和角色信息放入db。这是我实体的简单结构。
@Entity
@Table(name = "users")
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private Long userId;
@OneToMany(mappedBy = "users", fetch = FetchType.LAZY, orphanRemoval=true, cascade = CascadeType.ALL)
private List<UserRoleMapping> userRoleMapping;
}
//
@Entity
@Table(name = "user_role_mapping")
public class UserRoleMapping {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_role_mapping_id")
private Long userRoleMappingId;
@ManyToOne(fetch = FetchType.LAZY)
private Users users;
@ManyToOne(fetch = FetchType.LAZY)
private UserRole userRole;
}
//
@Entity
@Table(name = "users_role")
public class UserRole {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "role_id")
private Long roleId;
@Column(name = "role")
private String role;
@Column(name = "role_desc")
private String roleDesc;
@OneToMany(mappedBy = "userRole", fetch = FetchType.LAZY, orphanRemoval=true)
private List<UserRoleMapping> userRoleMapping;
}
在我的用例中,我必须确保在创建用户时,然后必须插入子序列userRoleMapping。并且,如果删除了userRole,则也必须删除userRoleMapping。
因此,我将CascadeType.ALL和orphanRemoval = true放在用户实体中,并将orphanRemoval = true放在userRole实体中。
但是,当我运行userRoleRepository.delete(userRole)时。我有dataIntegrityViolationException。
我对此进行了一些研究,并了解它是确保我们也删除父级(用户)的一种jpa约束。
我可以问一下我的用例是否有任何解决方法?
谢谢
答案 0 :(得分:0)
这是我的用例的解决方案。而不是在两个实体中都使用OneToMany,我应该使用ManyToMany关系。这很有意义,因为我暂时不关心Java逻辑中的映射。这是我的代码
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private Long userId;
@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.MERGE, CascadeType.PERSIST })
@JoinTable
private Set<UserRole> userRole;
}
//
public class UserRole {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "role_id")
private Long roleId;
@Column(name = "role")
private String role;
@Column(name = "role_desc")
private String roleDesc;
@OneToMany(mappedBy = "userRole", fetch = FetchType.LAZY)
private Set<Users> users;
}