我有一个使用Spring-data-rest暴露REST API的Spring Boot应用程序。我的一些实体具有OneToMany映射:
@Entity
@Table(name = "records")
@Getter
@Setter
public class Record {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "unique_record_id")
private long id;
...
@ManyToOne
@JoinTable(name = "cycles_records", joinColumns = @JoinColumn(name = "unique_record_id"), inverseJoinColumns = @JoinColumn(name = "unique_cycle_id"))
private Cycle cycle;
}
@Entity
@Table(name = "cycles", uniqueConstraints = @UniqueConstraint(columnNames = { "user_id", "cycle_id" }))
@Getter
@Setter
public class Cycle {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "unique_cycle_id")
private long id;
...
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "cycles_records", joinColumns = @JoinColumn(name = "unique_cycle_id"), inverseJoinColumns = @JoinColumn(name = "unique_record_id"))
private List<Record> records;
}
两个实体都有相应的存储库。
将新记录发布到属于某个周期的集合时,我只需将以下请求发送到/records
:
{
...record parameters
"cycle": "/cycles/1"
}
这将创建一个新实体并将其添加到相应的循环中。我现在正试图在我的itnegration测试中测试这种行为,我想知道是否有简单的方法如何使用对象,而不是在String中手动创建请求的主体:
@Test
public void test() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
// Record record = new Record();
// set record parameter here
// how to set the Cycle URI using objects???
// this feels clumsy
String record = "{\n ...parameters...,\n \"cycle\":\"/cycles/1\"\n}";
final ResponseEntity<Record> response = testRestTemplate.postForEntity("/records",
new HttpEntity<>(record, headers), Record.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
}
有没有办法如何将Record实体准备为Object并将其传递给RestTemplate,以便它包含指向所需Cycle实体的链接,还是我必须在String中准备它?
我希望我的问题有道理,如果没有,请随时澄清。