For the benefit of anyone else who comes across this thread my entities ended up being:
Post subject: FK on ManyToOne is null when saved Reply with quote
Hello,
One of my child entitys is saving with a null FK.
The setup should be like so:
Event has ManyToOne with Project (bidirectional)
Project has OneToMany with Task (bidirectional)
Task has ManyToOne with Plan.
I want to be able to save a Event and persist both the Project and the task (note Task is not a direct child of Episode, but a child of Project - which in turn is a child of event)
My Entity setup:
Code:
@Entity
public class Event {
public Event() {}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//
@ManyToOne(cascade = CascadeType.ALL)
private Project project;
@Entity
public class Project {
public Project() {}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//
@OneToMany(mappedBy = "project", fetch = FetchType.EAGER)
private List<Task> tasks;
@OneToMany(mappedBy = "project")
private List<Event> event;
@Entity
public class Task {
public Task() {}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//
@ManyToOne(optional=false)
@JoinColumn(name="project_id")
private Project project;
In order to insert the correct references (something with I initally thought Hiberante did auto-magically) I needed some code in my service layer. This is my attempt at it:
Code:
@Override
@Transactional
public Event submitProject(Event event) {
// SAVE PROJECT & TASKS
List<Event> eventList = new ArrayList<>();
eventList.add(event);
event.getProject().setEvent(eventList);
projectRepository.save(event.getProject());
taskRepository.save(event.getProject().getTasks());
// SETUP PROJECT TO KNOW WHAT EVENTS ITS RELATED TO (A COLLETION)
episode.getPlan().getEpisode();
// FOR EACH TASK THAT DOESNT HAVE PROJECT_ID - ADD IT
for (Task tasks : event.getProject().getTasks()) {
if (tasks.getProject() == null) {
tasks.setProject(event.getProject());
}
}
// A TEST TO NAVIGATE FROM BOTTOM UP
List<Task> tempTask = event.getProject().getTasks();
Task task = tempTask.get(2);
Project testProject = task.getProject();
List<Event> testEvent = testProject.getEvent();
// SAVE EVENT
return eventRepository.save(event);
}
If anyone wants to suggest improvements please do.
NB: I have not yet impliemnted a service to get a colletion of the existing events associated to a Project so it just associates the one.