简体   繁体   中英

How do I insert data in a @JoinColumn column in Spring Boot?

When I pass data by POST request to my TodoItem model, only the columns specified by @column get filled in, but the @JoinColumn column is null even if I use the column name in the JSON I'm sending over. My GET request API work just fine however, so I omitted them from controller code.

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
}

My constructor doesn't mention user_id , don't think it needs it though, but I may be wrong.

TodoController.java

@RestController
@RequestMapping("/api")
public class TodoController {

@Autowired
private UserRepository userRepository;

@Autowired
private TodoRepository todoRepository;

@PostMapping("/addItem")
public TodoItem addTodoItem(@RequestBody TodoItem todoItem) {
    return this.todoRepository.save(todoItem);
}
}

I send POST to http://localhost:8080/api/addItem

Request:

{
  "todo": "finish portfolio",
  "completed": false,
  "user_id": 1
}

However in my MySQL workbench, todo and completed get populated properly but user_id says null

In spring data (using hibernate or JPA), when saving entity which has reference to another entity. you must first fetch the referenced object first by id and then set it using setter in persistence entity. after that you can save and get (FK column) to be saved.

for example you first must use user repository and call

User user = userRepository.findById(userId);

and then

todoItem.setUser(user);

after that you can save item and FK column will get populated.

I think this the way to save reference entity. you can not relay on int id only.

also your request body JSON must be like this:

{
   "todo": "finish portfolio",
   "completed": false,
   "user": {
      "user_id":1
    }

}

also it best practice to define and use DTO object instead of entity itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM