问题描述:

I have two JPA entities Task and TaskList.

The Task class is this:

@Entity(name = "task")

public class Task implements Serializable {

// Id and 3 fields

@ManyToOne

@JoinColumn(name="tasklist_id")

private TaskList parentList;

// 3 more fields

// Constructor

public Task() {}

//Getters and Setters

}

and the TaskList class is this:

@Entity(name = "task_list")

public class TaskList implements Serializable {

// Id and two fields

@OneToMany(mappedBy="parentList")

private List<Task> tasks;

// Constructor

public TaskList() {}

}

When I do this:

TaskList parent_list = repo.findOne(listId);

Task t = new Task();

// set fields for t

parent_list.getTasks().add(t);

repo.save(parent_list);

It doesn't work. I get a null value for Task t.

If I use a repository for Task and save the task using its own repository, it works fine.

What I'd like to do is save both TaskList parent_list and Task t at the same time, using one call to parent_list's save() method and the relation in the entity classes.

How do I make this work?

网友答案:

Adding cascade attribute to oneToMany annotation and setting the parentlist for the newly created task should help.

相关阅读:
Top