Reputation: 13
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 ?
Upvotes: 1
Views: 1270
Reputation: 737
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.
Upvotes: 1