用户实体
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;
}
}
和地址实体
@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;
}
}
控制器代码
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = "users", method = RequestMethod.POST)
public void users(@RequestBody List<User> users) {
this.userRepository.save(users);
}
当我用psot man发布json数据时,数据是
[
{
"name":"yaohao",
"age":11,
"address":{
"city":"nantong"
}
},
{
"name":"yh",
"age":11,
"address":{
"city":"nantong"
}
}
]
当用户实体没有@Embedded地址实体时,代码工作正常,那么当我使用@Embedded注释时如何将json数据发布到控制器
答案 0 :(得分:0)
与@Embedded
的使用无关。在进行编组时,Jackson使用Java Bean属性来设置值,而User
类缺少getAddress
和setAddress
杰克逊只是忽略它,因为它不存在。
要修复为Address
添加getter和setter。
或者,不使用属性访问权限切换您的映射器以使用字段访问权限。有关详细信息,请参阅how to specify jackson to only use fields - preferably globally。