How to add a foreign key null value in Spring Boot? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to add a foreign key null value in Spring Boot? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I want to record to databse with foreign key is null. I know SpringBoot don’t allow do it. I tried record with @Query insert . But it cannot. I send data from client format JSON.

Entity City.

@Entity
@Table(name = "City")
public class City {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="ID_City")
Long idCity;

@Column(name="Name_City")
String nameCity;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "city")
private Collection<City> city;
/// getter and setter

Entity Person

@Entity
@Table(name = "Person")
public class Person {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="ID_Person")
Long idPerson;

@Column(name="Name")
String namePerson;

@Column(name="Phone")
String phonePerson;

@ManyToOne
@JoinColumn(name = "id_city")
private City city;

/// getter and setter

Data send to SpringBoot

 {
    "namePerson": "New person",
    "phonePerson": "0999999",
    "city": {
        "idCity": "",
        "nameCity": ""
    }
}

Question

Is there any way to set value NULL for foreign key ?

Answer

You should remove the city attribute entirely from your JSON.

Your JSON should look like this:

{
    "namePerson": "New person",
    "phonePerson": "0999999"
}

That way your city field in Person object will be set to null, consequently storing null as a foreign key in a database.

We are here to answer your question about How to add a foreign key null value in Spring Boot? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji