Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

spring boot - @OneToMany and @ManyToOne Jpa

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...