【发布时间】:2017-09-30 16:50:39
【问题描述】:
我正在尝试在 User 和 UserRole 两个实体之间创建 ManyToMany 关系。
我需要在映射表UserToRoleMapping 中添加一些额外的列,因此我创建了一个用于映射表的实体,其中包含额外的列(如createdDate 或isActive)。
现在的问题是 JPA 忽略映射表 userRoleMappingId 列上的 @Id 和 @GeneratedValue 注释,并使用 userId, roleId 创建复合主键。没关系。由于userRoleMappingId 列不是主键,我不再需要它,但是一旦我删除它,JPA 就会抱怨它需要一个带有@Id 注释的列。
即使我保持原样,当使用spring data repository for User保存带有某些角色的User时,它会抛出userRoleMappingId列不能为空的异常,因为存储库不会尝试为映射表生成ID,它被设置为not null。
理想情况下,我希望在带有序列生成器的映射表中拥有一个主键。
创建带有额外列的 JoinTable 的正确方法是 实体?
这是一个包含示例代码的 github 存储库,用于重现问题。
https://github.com/ConsciousObserver/SpringBootJoinTableIssue.git
以下是实体代码
@Entity
@SequenceGenerator(name="USER_SEQ")
class User {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="USER_SEQ")
private long userId;
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(name="UserRoleMapping", joinColumns=@JoinColumn(name="userId"), inverseJoinColumns=@JoinColumn(name="roleId"))
private Set<Role> roles;
/*getters and setters */
}
@Entity
@SequenceGenerator(name="ROLE_SEQ")
class Role {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ROLE_SEQ")
private long roleId;
/*getters and setters */
}
@Entity
@SequenceGenerator(name="USER_ROLE_SEQ")
class UserRoleMapping {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="USER_ROLE_SEQ")
private long userRoleMappingId;
@OneToOne
@JoinColumn(name="userId")
private User user;
@OneToOne
@JoinColumn(name="roleId")
private Role role;
private Date createdDate;
/*getters and setters */
}
【问题讨论】:
标签: spring spring-boot spring-data spring-data-jpa