1

the user entity

import javax.persistence.*;

@Entity
public class User {

@Id
@GeneratedValue
private Long id;

@Column(nullable = false)
private String name;

@Column(nullable = false)
private Integer age;

@Embedded
private Address address;

public User(){}

public User(String name, Integer age,Address address) {
    this.name = name;
    this.age = age;
    this.address = address;
}

public User(String name, Integer age) {
    this.name = name;
    this.age = age;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Integer getAge() {
    return age;
}

public void setAge(Integer age) {
    this.age = age;
}

}

and the address entity

@JsonInclude(JsonInclude.Include.NON_NULL)
@Embeddable
public class Address {

private String city;

public Address() {
}

public Address( String city) {
    this.city = city;

}



public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}


}

the controller code

   @ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = "users", method = RequestMethod.POST)
public void users(@RequestBody List<User> users) {
    this.userRepository.save(users);

}

when i post json data with psot man, the data is

[
 {
  "name":"yaohao",
  "age":11,
  "address":{
    "city":"nantong"
 }

  },
  {
  "name":"yh",
  "age":11,
   "address":{
    "city":"nantong"
  }

 }
]

the address always null

when the user entity has no @Embedded address entity,the code works fine,so how can i post json data to controller when i use @Embedded annotations

1 Answers1

0

It has nothing to do with the use of @Embedded. When doing the marshaling Jackson uses Java Bean properties to set the values and as your User class is lacking a getAddress and setAddress Jackson simply ignores it because it doesn't exists.

To fix add the getter and setter for Address.

Or instead of using property access switch your mapper to use field access. See how to specify jackson to only use fields - preferably globally for more information on that.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224