Java POST后返回具有@ManyToOne关系的保存实体
我有一个spring boot应用程序,它有一个名为Java POST后返回具有@ManyToOne关系的保存实体,java,spring,spring-boot,Java,Spring,Spring Boot,我有一个spring boot应用程序,它有一个名为Person的实体,它与@manytone有一种关系: @Entity public class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; @ManyToOne priva
Person
的实体,它与@manytone
有一种关系:
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String firstName;
private String lastName;
@ManyToOne
private Country country;
// ...
}
PersonController
用于获取现有人员和发布新人员:
@RestController
public class PersonController {
private final PersonRepository personRepository;
@Autowired
public PersonController(final PersonRepository personRepository) {
this.personRepository = personRepository;
}
@GetMapping("/person/{personId}")
public Person getPerson(@PathVariable long personId) {
return personRepository.findById(personId).get();
}
@PostMapping("/person_save_and_return_by_id")
public Person personSaveAndReturnById(@RequestBody Person person) {
Person savedPerson = personRepository.save(person);
// the payload sent by the client does not necessarily include all
// properties of the Country class, it might contain just the id.
// Therefore, we fetch the person from the database, so that all
// necessary JOIN operations are made and no properties are set to null.
Person samePerson = personRepository.findById(savedPerson.getId()).get();
return samePerson;
}
}
我想发布
新人,而不必完整描述现有的国家
,我只想表示其id:
curl-i-X POST-H“内容类型:application/json”-d'{“firstName”:“Frodo”,“lastName”:“Baggins”,“country”:{“id”:1}”http://localhost:8080/person_save_and_return_by_id
不幸的是,返回的实体的所有国家属性(id除外)都设置为空:
{
"firstName" : "Frodo",
"id" : 4,
"lastName" : "Baggins",
"country" : {
"id" : 1,
"description" : null,
"countryCodeIso" : null
}
}
POST请求按其应该的方式将所有内容插入数据库。例如,如果我GET
刚刚发布的对象:
curl-ihttp://localhost:8080/person/4
返回的json看起来与它应该的完全一样:
{
"lastName" : "Baggins",
"firstName" : "Frodo",
"country" : {
"id" : 1,
"countryCodeIso" : "FR",
"description" : "France"
},
"id" : 4
}
但是这对我没有帮助,因为我需要用创建新的人的相同方法访问国家
实例
我的问题是,为什么新创建的人在@PostMapping
方法中将某些属性设置为null的国家/地区,而完全相同的人在之后调用的@GetMapping
中没有这些null值?如何在@PostMapping
期间正确访问此人的国家/地区,而无需借助解决方法,例如通过其id显式获取国家/地区
该代码也可在上获得。它使用H2数据库,但我对hibernate和postgresql也有同样的问题。请注意,在启动过程中插入了两个国家,因此当国家id设置为1或2时不会引发外键冲突。是否尝试添加
@ManyToOne(cascade=CascadeType.MERGE)根据有效负载中提供的国家/地区id,您只能从存储库中获取国家/地区。然后将整个国家/地区对象设置为Person并保存Person。不起作用:persistentObject异常:分离的实体传递给persistent:hello.country
。我只是希望能够引用现有的国家ID。获取国家并不是为了保存个人,因为实体是正确持久化的。从给定id获取国家/地区以访问国家/地区属性是可行的,但我仍然不明白为什么我不能通过@PostMapping
中的人访问国家/地区,而不具有空值。也许某个fetchType适用于该权限?但这对我来说只是一个猜测。既不是FetchType.EAGER,也不是FetchType.LAZY。