我有一个spring mvc应用程序,用户可以在其中预定会议室。当我尝试通过使用deleteById()删除预订时,属于该预订的用户也会被删除。我该如何预防?
预订对象:
package spe_booker.models;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
@Entity
public class Booking {
@Id
@GeneratedValue
private Long id;
@NotNull
private Date startDateTime;
@NotNull
private Date endDateTime;
@NotNull
@ManyToOne(cascade = CascadeType.ALL)
private Room room;
@NotNull
@ManyToOne(cascade = CascadeType.ALL)
private User user;
private Date creationDate;
public Booking() { }
...getters and setters...
用户对象:
package spe_booker.models;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue
private Long id;
private String username;
String name;
private String password;
private String faculty;
private String role;
private Boolean blacklisted;
@Column(name = "enabled")
public int enabled;
@OneToMany(mappedBy = "user")
private List<Booking> bookings = new ArrayList<>();
...getters and setters...
预订资料库:
package spe_booker.Repositorys;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import spe_booker.models.Booking;
import spe_booker.models.User;
import java.util.List;
@Repository
public interface BookingRepository extends CrudRepository<Booking, Long> {
List<Booking> findAll();
List<Booking> findBookingsByUser(User user);
}
删除呼叫:
bookingRepository.deleteById(id);
答案 0 :(得分:0)
更改
的级联@NotNull
@ManyToOne(cascade = CascadeType.ALL)
private User user;
设置为适当的值。您是否更改用户,然后同时保存预订和用户?您是否同时与用户创建预订?如果您可以用“否”回答这些问题,则可以完全删除(cascade = CascadeType.ALL)
。并且您应该问自己为什么级联首先出现!
答案 1 :(得分:0)
CascadeType.ALL
强制JPA层叠所有操作(持久,删除,更新...)。也就是说,当您删除/更新预订时,它也会同时删除/更新房间和用户对象