Java Spring数据JPA ManyTone和OneToMany-找不到ID为的实体

Java Spring数据JPA ManyTone和OneToMany-找不到ID为的实体,java,hibernate,jpa,spring-data-jpa,Java,Hibernate,Jpa,Spring Data Jpa,我有三个表-角色,用户,和用户角色。这应该是ManyToMany,但由于我还想为user\u角色生成id,所以我使用了OneToMany和ManyToOne 以下是仅包含相关字段的我的实体: @Entity public class Role { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Integer id; @OneToMany(fetch = FetchType.EAGER,

我有三个表-
角色
用户
,和
用户角色
。这应该是
ManyToMany
,但由于我还想为
user\u角色生成id
,所以我使用了
OneToMany
ManyToOne

以下是仅包含相关字段的我的实体:

@Entity
public class Role {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Integer id;
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "role")
    private Set<UserRole> userRoles;
}

@Entity
public class User {
    @Id
    private String id;
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
    private Set<UserRole> userRoles;
}

@Entity
public class UserRole {
    @Id
    private String id;
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;
    @ManyToOne
    @JoinColumn(name = "role_id")
    private Role role;  
}

请帮帮我。谢谢。

斯特恩说得很有道理。您试图只保存用户
实体,但没有任何级联设置。因此,当您调用
userRepository.save(user)
时,显然缺少角色实体。在保存
user
之前保存依赖实体,或者在用户类中的
userRoles
字段上方添加级联,等等。

斯特恩的观点很有道理。您试图只保存用户
实体,但没有任何级联设置。因此,当您调用
userRepository.save(user)
时,显然缺少角色实体。在保存
用户之前保存依赖实体,或者最好在用户类中的
用户角色
字段上方添加级联。

如其他地方所述,您至少需要:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "user" , cascade = CascadeType.ALL)
private Set<UserRole> userRoles;

在继续之前,否则将不会填充列表。

如其他地方所述,您至少需要:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "user" , cascade = CascadeType.ALL)
private Set<UserRole> userRoles;

在持久化之前,否则将不会填充列表。

尝试将
cascade=CascadeType.ALL
添加到
@OneToMany(fetch=FetchType.EAGER,mappedBy=“user”,cascade=CascadeType.ALL)
@SternK only user?角色呢?哇!它起作用了。我相信我已经做到了,但不同的是,我还把它添加到了角色中。但现在我只向用户添加了它,它正在工作。我可以确认,将相同的添加到角色会带来另一个问题。所以向用户添加级联就足够了。谢谢。尝试将
cascade=CascadeType.ALL
添加到
@OneToMany(fetch=FetchType.EAGER,mappedBy=“user”,cascade=CascadeType.ALL)
@SternK only user?角色呢?哇!它起作用了。我相信我已经做到了,但不同的是,我还把它添加到了角色中。但现在我只向用户添加了它,它正在工作。我可以确认,将相同的添加到角色会带来另一个问题。所以向用户添加级联就足够了。非常感谢。
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user" , cascade = CascadeType.ALL)
private Set<UserRole> userRoles;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user" , cascade = 
        CascadeType.PERSIST)
private Set<UserRole> userRoles;
// for each UserRole in the list.
userRole.setUser(user);