我有一个产品表
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Product extends AuditModel {
@Id
@SequenceGenerator(name="optimized-sequence",sequenceName = "seq_product")
private Integer id;
private String sku;
private String description;
@NotNull
private String name;
***
***
***
@ManyToOne(optional = true)
@JoinColumn(name = "category_id")
@OnDelete(action = OnDeleteAction.NO_ACTION)
private Category category;
@ManyToOne(optional = true)
@JoinColumn(name = "manufacturer_id")
@OnDelete(action = OnDeleteAction.NO_ACTION)
private Manufacturer manufacturer;
@OneToMany(mappedBy = "product")
private List<OrderProduct> orderProducts;
}
还有一个 CrudRepository
public interface ProductRepository extends PagingAndSortingRepository<Product, Integer> {
Product findFirstBydescription(@Param("description")String description);
}
当我默认情况下调用端点/products时,我会得到这样的所有产品的列表
{
"_embedded" : {
"products" : [ {
"createdAt" : "2019-11-15T08:56:23.393+0000",
"updatedAt" : "2019-11-15T08:56:23.393+0000",
"id" : 802,
"sku" : null,
"name" : " product 1",
"description" : "description one",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/products/802"
},
"product" : {
"href" : "http://localhost:8080/api/products/802{?projection}",
"templated" : true
},
"manufacturer" : {
"href" : "http://localhost:8080/api/products/802/manufacturer"
},
"orderProducts" : {
"href" : "http://localhost:8080/api/products/802/orderProducts"
},
"category" : {
"href" : "http://localhost:8080/api/products/802/category"
}
}
}, .......
如何调用默认端点/products,在 json 对象产品内获取相关对象(Catefory、Manufacturer...)?
谢谢
最佳答案
如果我理解正确的话,您应该在 @ManyToOne 或 @OneToOne 注释中使用 FetchType.EAGER 策略来从数据库中获取所有相关数据。
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "category_id")
@OnDelete(action = OnDeleteAction.NO_ACTION)
private Category category;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "manufacturer_id")
@OnDelete(action = OnDeleteAction.NO_ACTION)
private Manufacturer manufacturer;
@OneToMany(mappedBy = "product", fetch = FetchType.EAGER)
private List<OrderProduct> orderProducts;
关于java - Spring:如何使用 CrudRepository 默认返回具有实体连接引用的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58878462/