gpt4 book ai didi

java - 删除多对多条目,同时将两个对象都保留在数据库中

转载 作者:行者123 更新时间:2023-11-30 10:06:48 26 4
gpt4 key购买 nike

我目前在事件和用户之间存在多对多关系。我的数据库中自动生成的名为 event_registrations 的表会跟踪关系以及哪个用户根据他们的 ID 去哪个事件。

我想要做的是有一个 Controller 方法,它接收事件 ID 和用户 ID 列表,以便从给定事件中删除给定用户。

这是我的模型类:

@Entity
public class Event {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToMany(mappedBy = "eventRegistrations")
private List<User> userList;

public Event() { this.userList = new ArrayList<>(); }

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public List<User> getUserList() {
return userList;
}

public void registerUser(User user){
this.userList.add(user);
}
public void removeUserRegistration(long userId){
this.userList.removeIf(user -> user.getId() == userId);
}
}


@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;

@ManyToMany
@JsonIgnore
@JoinTable(
name = "event_registrations",
joinColumns = @JoinColumn(name="user_id", referencedColumnName =
"id"),
inverseJoinColumns = @JoinColumn(name = "event_id",
referencedColumnName = "id"))
private List<Event> eventRegistrations;

public Integer getId() {
return id;
}

public List<Event> getEventRegistrations() {
return eventRegistrations;
}

public void setEventRegistrations(List<Event> eventRegistrations) {
this.eventRegistrations = eventRegistrations;
}
}

到目前为止,我在 EventController 中尝试过的内容:

@DeleteMapping(value = "/{id}/registrations", consumes = 
{"application/json"})
public ResponseEntity deleteEventRegistrations(@RequestBody ArrayList<Long>
data, @PathVariable("id") long id){
try {
Event event = eventService.getEventById(id);
data.forEach(userId -> event.removeUserRegistration(userId));
return ResponseEntity.ok().build();
} catch(DataNotFoundException ex){
return ResponseEntity.notFound().build();
}
}

这运行没有问题,但之后条目仍然存在于连接表中。对此进行调试时,用户确实会从 Event 对象中删除,但更改不会持久保存到数据库中。

感谢任何帮助!

最佳答案

@Entity
public class Event {

@ManyToMany(mappedBy = "eventRegistrations")
private List<User> userList;

}

这里的mappedBy是指UsereventRegistrations列表用来维护这个多对多的关系,也就是说Hibernate会更新基于 User 的 eventRegistrations 列表内容的关系表 (event_registrations)。你必须反过来做,从用户的事件列表中删除该事件:

public void removeUserRegistration(long userId){
//remove the event from the given user 's event list
for(User user : userList){
if(user.getId().equals(userId)){
user.getEventRegistrations().removeIf(event->event.getId().equals(this.id));
}
}

//remove given user from the event 's user list
//This will not have effects on DB record (as mentioned above) but suggest to also do it for keep the data in java model to be consistency.
this.userList.removeIf(user -> user.getId() == userId);
}

以上代码只是为了展示思路。您可能需要对其进行抛光。

关于java - 删除多对多条目,同时将两个对象都保留在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54493919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com