I'm learning Spring Framework, i followed some tutorials of relationship 1-1, so i defined my models: One Library have one Address.
I send in my body request the library data and the id from the address, the spring create the record, but he can't do the relationship, returning address null
and when i make a select in database, the address_id
is not saving in the table library
This is what i tried:
My model Library:
@Entity
@Table(name = "Bibliotecas")
public class Library implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
@OneToOne
@JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;
public Library() {
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
}
My model Address:
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false)
private String location;
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
@OneToOne(mappedBy = "address", fetch = FetchType.LAZY, optional = false)
private Library library;
}
My repositories:
public interface LibraryRepository extends JpaRepository<Library, Long> {}
public interface AddressRepository extends JpaRepository<Address, Long> {}
My library resource:
@RestController
@RequestMapping(value = "/api")
public class LibraryResource {
@Autowired
LibraryRepository libraryRepository;
@GetMapping("/libraries")
public List<Library> listaBibliotecas() {
return libraryRepository.findAll();
}
@PostMapping("/library")
public Library salvaBiblioteca(@RequestBody Library library) {
return libraryRepository.save(library);
}
}
I do this request in Postman:
{
"name": "library test",
"address_id": 1
}
Obs: i have one address with id 1 in database, but i receive:
{
"id": 5,
"name": "Biblioteca test",
"address": null
}
Why i'm receiving null in my return? And why my register is not saving the address_id
?