我正在学习 Spring Framework,我遵循了一些关系 1-1 的教程,所以我定义了我的模型:一个库有一个地址。我从地址中发送我的正文请求库数据和 id,spring 创建记录,但他不能做关系,返回地址null
,当我在数据库中进行选择时,address_id
没有保存在表库中
这是我尝试过的:
我的模型库:
@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;
}
}
我的模特地址:
@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;
}
我的存储库:
public interface LibraryRepository extends JpaRepository<Library, Long> {}
public interface AddressRepository extends JpaRepository<Address, Long> {}
我的图书馆资源:
@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);
}
}
我在 Postman 中执行此请求:
{
"name": "library test",
"address_id": 1
}
Obs:我在数据库中有一个 ID 为 1 的地址,但我收到:
{
"id": 5,
"name": "Biblioteca test",
"address": null
}
为什么我在退货中收到 null ?为什么我的寄存器没有保存address_id
?