In my spring JPA project I have two entities, Task and Developer. List can assign to a Developer and one Task can have just one Developer. I mapped them:
Developer
@Entity
@Table(name = "DEVELOPER")
public class Developer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@OneToMany(targetEntity = Task.class , mappedBy = "developer",cascade=CascadeType.ALL, fetch = FetchType.LAZY)
private List<Task> taskList;
Task
@Entity
@Table(name = "TASK")
public class Task implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long taskId;
private String taskTitle;
@ManyToOne
@JoinColumn(name="developer_id")
private Developer developer;
When I assign a List of Task to a Developer, JSON format is:
{
"id": 1,
"name": "John",
"taskList": [
{
"taskId":2,
"taskTitle": "Do sth"
}
]
}
But the value of Developer in above Task object is null:
{
"taskId":2,
"taskTitle": "Do sth",
"developer": null
}
I expect to this developer property is not null and Developer and task have a bidirectional relationship. How can I solve this? I am new in Spring and Hibernate. Any help would be greatly appreciated.
might missing cascade=CascadeType.ALL
in @ManyToOne annotation, and in Java doc, it says: (Optional) The operations that must be cascaded to the target of the association.By default no operations are cascaded.
, https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/ManyToOne.html
Remove cascade=CascadeType.ALL
in Developer class and add @joinColumn
annotation, it will work.
Developer class will look like this-
@Entity
@Table(name = "DEVELOPER")
public class Developer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@OneToMany(targetEntity = Task.class , mappedBy = "developer", fetch = FetchType.LAZY)
@JoinColumn(name="task_developer_id")
private List<Task> taskList;
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.