我有一个用户类
@Entity(name = "users")
@Table(name = "users")
public class User implements UserDetails {
static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id", nullable = false)
private Long id;
@Column(name = "username", nullable = false, unique = true)
private String username;
@Column(name = "password", nullable = false)
private String password;
}
绑定到一个简单的存储库
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
}
我有一个具有嵌套用户对象的教师类
@Entity
@Table(name = "instructors")
public class Instructor {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "instructor_id", nullable = false, updatable = false)
private Long id;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id")
private User user;
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "course_id")
private List<Course> courses;
}
它与以下存储库一起保存
public interface InstructorRepository extends PagingAndSortingRepository<Instructor, Long> {
}
我发布的JSON
{
"user": {
"id": 1
}
}
当我尝试POST
到/instructors
时。用户无效。是否有一些我缺少的东西让JPA将两者结合在一起?我尝试将CascadeType.ALL
添加到字段上,并且只抛出一个分离的持久异常。
答案 0 :(得分:0)
将CascadeType.ALL
保留为Instructor
,就像您已经尝试过的那样:
@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
另外,将以下内容添加到User
。似乎和我一起工作。它提供了映射信息,并使JPA处理User
托管
@OneToMany(mappedBy="user")//, cascade=CascadeType.ALL)
private List<Instructor> instructors = new ArrayList<>();
我已在上面评论了cascadeType
,但如果您希望User
保留其Instructors
的全部内容,则可能会有用。