我的用户与我的地址表有一对一映射,它在用户表中有一个地址外键。我想在不删除用户的情况下删除用户地址,但由于我在用户表中有外键,因此无法删除,请帮助我在此处输入图像描述
@Table(name = "Address ")公共类地址{
@Id
@GeneratedValue
private Integer addressId;
@NotNull(message="City should not be null")
@Pattern(regexp="^[a-zA-Z]+$" ,message="City should contain only alphabets")
private String city;
@NotNull(message="State should not be null")
@Pattern(regexp="^[a-zA-Z]+$" ,message="State should contain only alphabets")
private String state;
@NotNull(message="Pincode should not be null")
@Size(min=6,max=6,message = "Size must be of 6 elements")
@Pattern(regexp="\\d+", message = "Pincode must contain only numbers")
private String pinCode;
@NotNull(message="House number should not be null")
@Pattern(regexp="\\d+", message = "Pincode must contain only numbers")
private String houseNo;
@NotNull(message="Landmark should not be null")
private String landmark;
我的用户类
@Entity
@Table(name = “UserDetails”) public class User { public enum Role{ADMIN,USER};'' @Id @GeneratedValue private Integer userId;
@NotNull(message = "Firstname should not be null")
@Pattern(regexp="^[a-zA-Z '.-]*$", message = "Name should be alphabetic")
private String firstName;
@NotNull(message = "Firstname should not be null")
@Pattern(regexp="^[a-zA-Z '.-]*$", message = "Name should be alphabetic")
private String lastName;
@Email
private String email;
private String password;
private Role role;
@OneToOne(cascade = CascadeType.ALL)
private Address address;
@OneToMany(mappedBy = "userDetails", cascade = CascadeType.ALL)
private Set<Order> orders = new HashSet<Order>();
private Address address;
@OneToMany(mappedBy = "userDetails", cascade = CascadeType.ALL)
private Set<Order> orders = new HashSet<Order>();
为了安全起见,请尝试添加< code>orphanRemoval=true。
@OneToOne(cascade = CascadeType.ALL, orphanRemoval=true)
private Address address;
然后,您应该能够通过将字段的值设置为空来删除地址,例如:
User user = userRepository.getById(1);
user.setAddress(null);
userRepository.save(user);
PERSIST不起作用?如果你想看看这里。
@OneToOne(cascade = CascadeType.PERSIST)
private Address address;
您收到的错误消息是什么?在数据库级别,您的外键“on delete set null”选项也需要设置。
删除时设置null