Home > Mobile >  How to delete a foeign key of address from user table?
How to delete a foeign key of address from user table?

Time:03-16

My user is havig one to one mapping with my address table , it has a foreign key of address in the user table. I want to delete the user address without deleting my user , but as i have the foreign key in the user table i am not able to do so, please help me outenter image description here

@Table(name = "Address") public class 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;

My User class

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

CodePudding user response:

PERSIST didn't work? If you want to have a look here.

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

CodePudding user response:

Try adding orphanRemoval=true just to be safe.

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

Then you should be able to delete the address by setting the value of the field to null such as:

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

CodePudding user response:

What’s the error message you are getting? At database level, your foreign key “on delete set null” option needs to be set as well.

Set null on delete

  • Related