【问题标题】:how i can post json to springboot controller with @Embedded in @Embeddable class我如何在@Embeddable 类中使用@Embedded 将json 发布到spring boot 控制器
【发布时间】:2017-10-31 03:47:36
【问题描述】:

用户实体

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"
  }

 }
]

the address always null

当用户实体没有@Embedded地址实体时,代码可以正常工作,那么当我使用@Embedded注解时如何将json数据发布到控制器

【问题讨论】:

  • 你没有 Address 的 getter 和 setter。

标签: spring spring-mvc jpa spring-boot spring-data-jpa


【解决方案1】:

@Embedded的使用无关。在执行封送处理时,Jackson 使用 Java Bean 属性来设置值,并且您的 User 类缺少 getAddresssetAddress Jackson 只是忽略它,因为它不存在。

修复为Address 添加getter 和setter。

或者不使用 property 访问,而是将您的映射器切换为使用 field 访问。有关更多信息,请参阅how to specify jackson to only use fields - preferably globally

【讨论】:

    猜你喜欢
    • 2013-02-16
    • 2016-07-05
    • 2012-10-03
    • 2013-01-11
    • 2021-06-05
    • 2011-04-28
    • 1970-01-01
    • 2011-08-19
    相关资源
    最近更新 更多