我有两个实体:
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(nullable = true)
private String name;
@OneToMany(mappedBy = "order",
cascade = CascadeType.ALL)
private List<Product> products = new ArrayList<>();
public void addProduct(Product product) {
products.setOrder(this);
getProducts().add(product);
}
}
第二个:
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(targetEntity = Order.class)
@JoinColumn(name = "product_id", referencedColumnName = "id")
private Order order;
}
控制器:
@RestController
@RequestMapping("/api")
public class PersistenceController {
@Autowired
private OrderRepository repository;
@PostConstruct
private void init() {
Order order = new Order();
order.setName("some_order");
Product product = new Product();
order.addProduct(product);
repository.save(order);
}
@RequestMapping(value = "/getAll", method = RequestMethod.GET)
@ResponseBody
List<Order> getAll() {
return repository.findAll();
}
}
例外情况如下:
无法写入HTTP消息: org.springframework.http.converter.HttpMessageNotWritableException: 无法写内容:无法设置字段值[Product(id = 1, order = null)]通过反射的值 :[class model.entities.Product.order] setter of model.entities.Product.order(通过引用链: 的java.util.ArrayList [0] - &GT; model.entities.RoomEntity [ “产品”]);嵌套 异常是com.fasterxml.jackson.databind.JsonMappingException: 无法设置字段值[Product(id = 1,day = null,startHour = null, endHour = null,order = null)]通过反射的值:[class model.entities.Product.order] model.entities.Product.order的setter (通过参考链: java.util.ArrayList [0] - &gt; model.entities.Order [“products”])2017-04-15 17:38:36.073 WARN 18200 --- [nio-8091-exec-1] o.h.e.loading.internal.LoadContexts:HHH000100:故障安全清理(集合): org.hibernate.engine.loading.internal.CollectionLoadContext@3713fa6c 2017-04-15 17:38:36.073 WARN 18200 --- [nio-8091-exec-1] o.h.e.l.internal.CollectionLoadContext:HHH000160:开 CollectionLoadContext#cleanup,localLoadingCollectionKeys包含 [1]条目