【发布时间】:2015-10-06 13:29:12
【问题描述】:
我正在使用 SpringBoot 和 JPA 来构建 REST 接口。
现在,我为从数据库中获取的产品列表返回了一个奇怪的 JSON。假设我有:
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "categoryId", nullable = false, updatable = false)
private Category category;
...
}
@Entity
public class Category implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy = "category", cascade = CascadeType.DETACH)
@OrderBy("name ASC")
private List<Product> products = Collections.emptyList();
...
}
Product 的 JPA 存储库定义为:
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findAll();
}
在我的控制器中,我有:
@Autowired
private ProductRepository productRepo;
@RequestMapping("/all-products", method = RequestMethod.GET)
public Map<String,Object> home() {
Map<String,Object> model = new HashMap<String,Object>();
model.put("products", productRepo.findAll());
return model;
}
让我发疯的是,如果我尝试如下调用此服务:
$ curl localhost:8080/all-products
由于表 product 和 category 之间的关系,我得到一个递归输出,例如:
{"products":[{"id":1,"name":"Product1","category":
{"id":1,"name":"Cat1","products":[{"id":6,"name":"Product6","category":
{"id":1,"name":"Cat1","products":[{"id":6,"name":"Product6","category":
{"id":1,...
我做错了什么?
【问题讨论】: