如何通过RestTemplate对具有嵌入成员的类进行POST



我有一个有几个成员的类,以及相关的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元素:

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);

在值为AL的嵌入成员尚未出现在数据库中的情况下,我仍然会在Tester表中创建一个新行。。。但Tester中的值和名称列填充了为FacilityType定义的值(AL和2adamlec)。

请注意,我们使用的是FacilityType和Tester的JPARepository框架。因此,CRUD函数是"秘密"处理的,我无法调试POST处理。我想知道这是否与GET for Tester数据只返回JSON回复中的基元字段有关,因为没有为FacilityType定义投影。

我是否做错了什么,导致保存FacilityType字段来代替测试仪表中所需的测试仪字段?

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

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向下移动,以获得到嵌入式类实例的链接。

最新更新