我已经映射了两个类之间的双向关系。情况就是这样:我有旅行和用户。用户应该能够订阅旅行并取消订阅。所以我不想删除对象,只删除连接表中的行。目前,订阅部分有效,但不能取消订阅。
当我测试它时,更改是在内存中进行的,而不是在数据库中进行的。可能有什么不对?我的代码如下所示。
跳闸:
@ManyToMany(mappedBy = "enrolledExecutionMoments", cascade = {
CascadeType.ALL, CascadeType.ALL }, fetch = FetchType.EAGER)
private List<User> tripExecutionMomentParticipators = new ArrayList<User>();
public TripExecutionMoment() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@JsonIgnore
public List<User> getTripExecutionMomentParticipators() {
return tripExecutionMomentParticipators;
}
public void setTripExecutionMomentParticipators(
List<User> tripExecutionMomentParticipators) {
this.tripExecutionMomentParticipators = tripExecutionMomentParticipators;
}
public void addEnrollement(User user) {
tripExecutionMomentParticipators.add(user);
}
public void removeEnrollement(User user) {
tripExecutionMomentParticipators.remove(user);
}
用户:
@Entity
@Table(name = "t_user")
public class User {
@Id
@GeneratedValue
private int id;
@NotBlank(message = "err_invalid_mail")
@Email(message = "err_invalid_mail")
private String email;
@ManyToMany(cascade = { CascadeType.ALL, CascadeType.ALL }, fetch = FetchType.EAGER)
@JoinTable(joinColumns = { @JoinColumn(name = "userId") }, inverseJoinColumns = { @JoinColumn(name = "tripExecutionMomentId") })
private List<TripExecutionMoment> enrolledExecutionMoments = new ArrayList<TripExecutionMoment>();
public User() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getId() {
return id;
}
@JsonIgnore
public TripExecutionMoment getCheckedInTripExecutionMoment() {
return checkedInTripExecutionMoment;
}
public void setCheckedInTripExecutionMoment(
TripExecutionMoment checkedInTripExecutionMoment) {
this.checkedInTripExecutionMoment = checkedInTripExecutionMoment;
}
public void addEnrollement(TripExecutionMoment tripExecutionMoment) {
enrolledExecutionMoments.add(tripExecutionMoment);
}
public void removeEnrollement(TripExecutionMoment tripExecutionMoment) {
enrolledExecutionMoments.remove(tripExecutionMoment);
}
}
这是我注册(订阅)和取消注册(取消订阅)
的代码@Transactional
public void enrollParticipator(User user,
TripExecutionMoment tripExecutionMoment)
throws AlreadyBoundException {
if (tripExecutionMoment.getTripExecutionMomentParticipators().contains(
user)) {
throw new AlreadyBoundException(
"This user is already enrolled for this trip");
}
tripExecutionMoment.addEnrollement(user);
user.addEnrollement(tripExecutionMoment);
getEntityManager().merge(tripExecutionMoment);
}
@Transactional
public void disenrollParticipator(User user,
TripExecutionMoment tripExecutionMoment) {
tripExecutionMoment.removeEnrollement(user);
user.removeEnrollement(tripExecutionMoment);
getEntityManager().merge(user);
}