Issue
I have a request body with data for two different object(entities), for example.
- Task (with field as description) and
- Subtasks (with field as description)
One request body will have one task description and one or many subtask descriptions.
e.g.
{
"task":
{
"description": "test1"
},
"subtask":
{
"description": "test1"
}
}
I want to be able to create the task entity first, use the auto generated ID for the task and use it to create the subtasks(subtask entity has a field taskid)
Controller
@PostMapping("/add")
public void add(@RequestBody NewTaskBody.TaskBody taskbody) {
taskService.saveTask(taskbody.task);
subTaskService.saveSubTask(taskbody.subtasks);
}
private static class NewTaskBody {
public static class TaskBody {
public Task task;
public SubTask subtasks;
}
}
Task Entity
@Entity
@Table(name = "tasks")
public class Task {
private @Id @GeneratedValue Long id;
private String description;
//getters and setters
}
SubTask Entity
@Entity
@Table(name = "subtasks")
public class SubTask {
private @Id @GeneratedValue Long id;
private Long taskid;
private String description;
//getters and setters
}
Task Service
@Service
@Transactional
public class TaskService {
@Autowired
private TaskRepository taskRepository; //this is just a interface using JPA
public List<Task> listAllTask() {
return taskRepository.findAll();
}
public void saveTask(Task task) {
taskRepository.save(task);
}
public Task getTask(Long id) {
return taskRepository.findById(id).get();
}
}
SubTask Service
@Service
@Transactional
public class SubTaskService {
@Autowired
private SubTaskRepository subtaskRepository; //this is just a interface using JPA
public void saveSubTask(SubTask subtask) {
subtaskRepository.save(subtask);
}
public SubTask getSubTask(Long id) {
return subtaskRepository.findById(id).get();
}
}
Question When I send the JSON using postman, the Task entity and row in underlyign dtabase is created but I get the below error (I suppose while processing subtasks)
"message": "Entity must not be null.; nested exception is java.lang.IllegalArgumentException: Entity must not be null.",
"path": "/add/"
Solution
The problem lies here.
private static class NewTaskBody {
The object in your controller is parsed by some library that converts the JSON
input into a request java object. In Spring by default this library is jackson
. If it is private, the jackson
would not be able to access this class in order to create the request object as you intend it to.
You should make it public
public static class NewTaskBody {
You should also add getters
and setters
in that nested class, so that jackson
could initialize the fields task
, subTasks
when needed.
Answered By - Panagiotis Bougioukos
Answer Checked By - Cary Denson (JavaFixing Admin)