[英]Want to include relationships in Spring REST API
我是春季新人。
我有三個實體Invoice, Line and Product
。
(1)如果我調用GET /invoices
那么我想要輸出,
{
"invoices": [
{
"id": "101",
"date": "2013-02-14"
},
{
"id": "102",
"date": "2013-02-18"
}
]
}
我已經做到了,我能夠做到,但是不能在get請求中包含關系。
(2)我想GET這樣的事情,包括關系。
GET /invoices?include=invoice.lines:embed,invoice_line.product:sideload
我想要輸出像
{
"invoices": [
{
"id": "101",
"date": "2013-02-14",
"lines": [
{
"id": "201",
"product_id": "301",
"amount": 100
},
{
"id": "201",
"product_id": "302",
"amount": 100
}
]
},
{
"id": "102",
"date": "2013-02-18",
"lines": [
{
"id": "203",
"product_id": "301",
"amount": 100
}
]
}
],
"products": [
{
"id": "301",
"name": "Ice Cream"
},
{
"id": "302",
"name": "Waffles"
}
]
}
我陷入(2)包含關系中,我想實現類似這種需要幫助的東西。 提前致謝。
您可以使用休眠注釋來做到這一點。
您的發票實體類應如下所示:
@Entity
@Table(name = "invoices") // your table name
public class Invoice implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "date")
private String date;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "invoices")
private Set<Line> line = new HashSet<Line>(0);
// getter and setter method
而且您的Line實體應如下所示:
@Entity
@Table(name = "lines")
public class Line implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@ManyToOne
@JoinColumn(name = "id", nullable = false) // Invoice id
private Invoice invoice;
// product_id and amount and getter and setter method
並確保您在數據庫中具有正確的關系。 您可以在這里查看完整的教程。
希望對您有所幫助,並祝您編程愉快。
更新:
發票的數據傳輸對象:
public class InvoiceDTO {
private Integer id;
private String date;
// getter and setter methods
}
然后創建另一個返回InvoiceDTO的服務:
Invoice invEntity = em.find(Invoice.class, id);
InvoiceDTO invDTO = new InvoiceDTO();
invDTO.setId(invEntity.getId());
invDTO.setDate(invEntity.Date());
return invDTO;
然后,在需要時可以返回關聯內的發票,也可以返回InvoiceDTO對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.