简体   繁体   English

POST后,使用@ManyToOne关系返回保存的实体

[英]Return saved entity with @ManyToOne relationship after POST

I have a spring boot application with an entity called Person , which has a @ManyToOne relationship: 我有一个名为Person的实体的Spring启动应用程序,该实体具有@ManyToOne关系:

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String firstName;
    private String lastName;

    @ManyToOne
    private Country country;
    // ...
}

The PersonController is used to allow to GET existing persons and POST new ones: PersonController用于允许GET现有人员和POST新人员:

@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;
    }
}

I would like to POST new persons without having to describe the existing Country in its entirety, I only want to denote its id: 我想POST新的人,而不必描述现有Country的全部,我只想表示其ID:

curl -i -X POST -H "Content-Type:application/json" -d '{"firstName": "Frodo", "lastName": "Baggins", "country": {"id": 1}}' http://localhost:8080/person_save_and_return_by_id

Unfortunately, the returned entity has all country properties, except for the id, set to null: 不幸的是,返回的实体具有除id之外的所有国家/地区属性,设置为null:

{
   "firstName" : "Frodo",
   "id" : 4,
   "lastName" : "Baggins",
   "country" : {
      "id" : 1,
      "description" : null,
      "countryCodeIso" : null
   }
}

The POST request inserts everything into the database as it should. POST请求将所有内容都插入到数据库中。 For instance, if I GET the object I just previously posted: 例如,如果我GET我之前发布的对象:

curl -i  http://localhost:8080/person/4 

The returned json looks exactly as it should: 返回的json看起来应该是这样的:

{
   "lastName" : "Baggins",
   "firstName" : "Frodo",
   "country" : {
      "id" : 1,
      "countryCodeIso" : "FR",
      "description" : "France"
   },
   "id" : 4
}

But that doesn't help me, because I need to access the Country instance in the same method where the new Person is created. 但这对我没有帮助,因为我需要在创建新Person的同一方法中访问Country实例。

My question is, why does the newly created person have a country with some properties set to null in the @PostMapping method, when the exact same person does not have those null values in the @GetMapping called right after? 我的问题是,为什么新创建的人在@PostMapping方法中有一个属性设置为null的@PostMapping ,当完全相同的人在@GetMapping之后没有那些空值时被调用? How can I access the person's country correctly during the @PostMapping , without resorting to workarounds such as explicitly fetching the country via its id? 如何在@PostMapping期间正确访问此人的国家/地区,而无需采用诸如通过其ID明确获取国家/地区的解决方法?

The code is also available on github . 代码也可以在github上找到 It uses the h2database, but I have the same issue with hibernate and postgresql. 它使用h2database,但我对hibernate和postgresql也有同样的问题。 Notice that two countries are inserted during startup, so no foreign key violations are thrown when the country id is set to 1 or 2. 请注意,在启动期间插入了两个国家/地区,因此当国家/地区ID设置为1或2时,不会引发外键冲突。

did you try to add 你试着添加吗?

@ManyToOne(cascade=CascadeType.MERGE) @ManyToOne(级联= CascadeType.MERGE)

You could fetch only country from the repository given the country_id you provide in the payload. 根据您在有效负载中提供的country_id,您只能从存储库中获取国家/地区。 Then set the whole country object to Person and save person. 然后将整个国家/地区对象设置为Person并保存人员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM