我如何 POST 通过 RestTemplate a class 嵌入成员?

How do I POST through RestTemplate a class with embedded members?

我有一个 class 有几个成员,以及相关的 setter 和 getter:

public class Tester implements Serializable {
  @Column(name="ID", nullable=false, unique=true)   
  @Id   
  @GeneratedValue(generator="LOCATION_FACILITYTYPE_ID_GENERATOR")   
  @org.hibernate.annotations.GenericGenerator(name="LOCATION_FACILITYTYPE_ID_GENERATOR", strategy="native") 
  private int ID;

  @Column(name="Value", nullable=false, unique=true, length=4)  
  private String value;

  @Column(name="Name", nullable=false, unique=true, length=8)   
  private String name;

  @ManyToOne(targetEntity=location.FacilityType.class, fetch=FetchType.LAZY)    
  @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.LOCK})  
  @JoinColumns({ @JoinColumn(name="FacilityTypeID", referencedColumnName="ID", nullable=false) })   
  private location.FacilityType facility;

在 JUnit 中,我正在尝试创建测试器元素:

    Tester trythis = new Tester();
    trythis.setName("Herewe");
    trythis.setValue("wow1");
    Tester jnode = restTemplate.postForObject(TestBase.URL + "tester/", trythis, Tester.class);

这按预期工作。但是,如果我使用这样的代码来包含嵌入式成员:

    FacilityType ft = new FacilityType();       
    ft.setValue("AL");
    ft.setName("2adamlec");
    Tester trythis = new Tester();
    trythis.setName("Herewe");
    trythis.setValue("wow1");
    trythis.setFacility(ft);
    Tester jnode = restTemplate.postForObject(TestBase.URL + "tester/", trythis, Tester.class);

其中 value=AL 的嵌入成员尚未出现在数据库中,我仍然在测试器中创建了一个新行 table ...但是测试器中的值和名称列已填充为 FacilityType 定义的值(AL 和 2adamlec)。

请注意,我们正在为 FacilityType 和 Tester 使用 JPARepository 框架。 CRUD 功能因此处理 'under the covers',我无法调试 POST 处理。我想知道这是否与测试人员数据的 GET 仅 return JSON 回复中的原始字段有关,因为没有为 FacilityType 定义投影。

我是否做错了什么导致 FacilityType 字段被保存以代替测试器中所需的测试器字段 table?

简短的回答:创建项目时,您必须以服务器期望的相同 JSON 格式提供数据。如果你有一个嵌入的class,你必须创建一个class,其中设施成员是一个字符串来容纳一个URL,然后将该成员设置为URL对应于嵌入的现有实例 class。在接收端,你还需要一个新的 class 像这样:

public class FMT_Tester_RCV {
  public FMT_Tester_RCV() { }

  private String value;
  private String name;
  private Integer id;
  private Integer ormid;
  private JsonNode _links;

您可以在其中向下移动 JsonNode 以获得 link 到嵌入式 class 实例。