I have a User
model and a TodoItem
model where the TodoItem
model has a primary key to the User
model with a user_id
@joincolumn. My issue is the response I get from the getUsers
API after I add an item. It creates this super long nested JSON where it repeats itself over and over again. I feel like I'm not handling the primary key case properly.
TodoController.java
@RestController
@RequestMapping("/api")
public class TodoController {
@Autowired
private TodoRepository todoRepository;
@PostMapping("/addItem")
public TodoItem addTodoItem(@RequestBody TodoItem todoItem) {
return todoRepository.save(todoItem);
}
User.java
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "name")
private String name;
@Column(name = "password")
private String password;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private List<TodoItem> todos;
public User() {
}
public User(String name, String password, List<TodoItem> todos) {
this.name = name;
this.password = password;
this.todos = todos;
}
// setter and getters
TodoItem.java
@Entity
@Table(name = "todo_item")
public class TodoItem {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "todo")
private String todo;
@Column(name = "completed")
private boolean completed;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
public TodoItem() {
}
public TodoItem(String todo, boolean completed) {
this.todo = todo;
this.completed = completed;
}
// setters and getters
Add Item Request
{
"todo": "blahblah",
"completed": false,
"user": {
"id": 6
}
}
Add Item Response
{
"id": 26,
"todo": "blahblah",
"completed": false,
"user": {
"id": 6,
"name": null,
"password": null,
"todos": null
}
}
So already I don't like the way the response is given, why is name, pass, and todos null when the user with id 6 exists, also I just passed it a todoitem, so why is todo null. The database populates properly, it's just that the response seems wrong. And then I think it ties into the main problem I have which is here; this is after I add item to a user:
Get Users Response
[
{
"id": 6,
"name": "joe",
"password": "pass",
"todos": [
{
"id": 26,
"todo": "blahblah",
"completed": false,
"user": {
"id": 6,
"name": "joe",
"password": "pass",
"todos": [
{
"id": 26,
"todo": "blahblah",
"completed": false,
"user": {
"id": 6,
"name": "joe",
"password": "pass",
"todos": [
{
"id": 26,
"todo": "blahblah",
"completed": false,
"user": {
"id": 6,
"name": "joe",
"password": "pass",
"todos": [
{
"id": 26,
"todo": "blahblah",
"completed": false,
"user": {
"id": 6,
"name": "joe",
"password": "pass",
"todos": [
{
"id": 26,
"todo": "blahblah",
And it just continues like that for literally thousands of lines. Even though the response is crazy, the database updates properly, but the API calls can take a while due to this issue