I have a User Class
@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;
}
Tied to a simple Repository
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
}
And I have an Instructor Class that has a nested User object
@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;
}
It is saved with the following repository
public interface InstructorRepository extends PagingAndSortingRepository<Instructor, Long> {
}
The JSON I am posting
{
"user": {
"id": 1
}
}
When I try to do a POST
to /instructors
. User is coming in null. Is there something I am missing to get JPA to tie the two together? I have tried adding CascadeType.ALL
onto the field and that only throws a detached persist exception.
Leave the CascadeType.ALL
to Instructor
like you already tried:
@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
In addition add the following to User
. Seems to work with me. It provides the mapping information and makes JPA treat User
managed
@OneToMany(mappedBy="user")//, cascade=CascadeType.ALL)
private List<Instructor> instructors = new ArrayList<>();
I have commented out the cascadeType
in the above but it might be useful if you want to persist User
wit all of its Instructors
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.