如何删除用户table的地址外键?

How to delete a foreign key of address from user table?

我的用户与我的地址table一对一映射,它在用户table中有一个地址外键。我想删除用户地址而不删除我的用户,但是因为我在用户中有外键table我不能这样做,请帮助我enter image description here

@Table(名称=“地址”) public class 地址 {

@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;

我的用户class

@Entity

@Table(name = "UserDetails") public class 用户 { public 枚举角色 {ADMIN,USER};`` @ID @生成值 私有整数 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>();

PERSIST 没用?如果你想看看here.

@OneToOne(cascade = CascadeType.PERSIST)
private Address address;

为了安全起见,请尝试添加 orphanRemoval=true

@OneToOne(cascade = CascadeType.ALL, orphanRemoval=true)
private Address address;

那么你应该可以通过将字段的值设置为空来删除地址,例如:

User user = userRepository.getById(1);
user.setAddress(null);
userRepository.save(user);

您收到的错误消息是什么?在数据库级别,您的外键“on delete set null”选项也需要设置。

Set null on delete