I have two entities that represent two tables in the database, similar to the concept of inheritance:
Entity Person:
@Entity
@Table(name ="person", schema = "myself")
public class Person implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="person_id")
private long id;
@Column(name = "person_name", nullable = false, length = 255)
@NotNull(message = "name_expects")
private String name;
@OneToOne(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = false, fetch = FetchType.LAZY)
@JsonIgnore
private AdressPerson adressPerson;
... get and setters
}
Entity Adress:
@Entity
@Table(name ="adress_person", schema = "myself")
public class AdressPerson implements Serializable {
@Id
@Column(name = "person_id")
private long id;
@Column(name = "type", nullable = false, length = 14)
private String type;
@Column(name = "adress", nullable = false, length = 255)
private String adress;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Person person;
... get and setters
}
I need to send a single request post and form-data with this:
{
"id":1,
"name":"John Doe",
"type": "home",
"adress" : "Madison Ave"
}
In my controller I need to receive this way:
...
@PostMapping(value = "", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
public AdressPerson addAdressPerson(@NotNull @RequestParam AdressPerson adressPersonRequest) {
//code
}
...
However I am not able to do the mapping, I have tried to use filter and RequestWrapper, but I was not able to overwrite the message body. Anyone can help me?
Thanks!
Spring's @RequestParam
maps query parameters, like ?name=something&address=some-address
While you're trying to make a POST request and want to deserialize JSON request payload into a java class.
Use @RequestBody
instead.
Within your @RestController class you can define your POST mapping method as follows:
...
@PostMapping(value = "")
public AdressPerson addPerson(@RequestBody Person person) {
//code
}
...
As a default, your spring-boot project expects / returns a JSON body, so you can omit the consumes and produces attributes.
Now for receiving the payload in above controller, your JSON request body should look like -
{
"id":1,
"name":"John Doe",
adressPerson": {
"type": "home",
"adress" : "Madison Ave"
}
}
Also, within your entity Person, remove @JsonIgnore from adressPerson field, instead try using @JsonManagedReference and @JsonBackReference.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.