问题
My User
class looks like this :
@Data
@Entity
public class User {
@Id
Long userID;
@ManyToMany(mappedBy = "admins")
private List<ClassRoom> classRooms = new ArrayList<>();
}
And my ClassRoom
class like this :
@Data
@Entity
public class ClassRoom {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long classRoomID;
@ManyToMany
@JoinTable(name ="classroom_user",
joinColumns = @JoinColumn(name = "classroom_id"),
inverseJoinColumns = @JoinColumn(name = "user_id"))
private List<User> admins = new ArrayList<>();
}
And in my UserController
class, I have :
@PostMapping("user/{id}/c")
User addClassRoom(@PathVariable Long id,@RequestBody ClassRoom newClassRoom)
{
logger.debug(repository.findById(id));
return repository.findById(id)
.map(user -> {
user.getClassRooms().add(newClassRoom);
user.setClassRooms(user.getClassRooms());
return repository.save(user);
})
.orElseGet(() -> {
return null;
});
}
And I POST and empty JSON ({}
) and I see no change in my users. The Classroom
or an empty Classroom
doesn't get added in the User
.
What is the problem here? How can I resolve this ?
回答1:
Can you paste the logs, please? Is Hibernate doing any insert into your table? Has the database schema been created in the DB correctly? One thing I recommend you to do is to add a custom table name on the top of your User class, using annotations like so: @Table(name = "users"). In most SQL dialects user is a reserved keyword, hence it is recommended to always annotate User class a bit differently, so that Hibernate won't have any problems to create a table for that entity.
回答2:
user.getClassRooms().add(newClassRoom);
is suffice, user.setClassRooms(user.getClassRooms());
not required.
You will have to perform cascade save operation.List all cascade types explicitly and don't use mappedBy, instead use joincolumns annotation.
回答3:
IMO you must find classRoom by its id from repository, if it's new, you must create a new entity and save it first. Then assign it to user and save it. The object you receive from the post method was not created by the entity manager.
来源:https://stackoverflow.com/questions/58258189/spring-boot-many-to-many-post-method-not-updating-data