![](/img/trans.png)
[英]OneToMany mapping not working in the Controller crud Spring Boot Rest API
[英]@OneToMany mapping in spring boot app
我在我的产品类中使用spring框架product
和productReview
之间存在@OneToMany
关系,因此我按如下方式映射了此关系,但是当我调用产品的findAll()
方法时,它给我一个错误的Bad String
我无法弄清楚是什么问题,当我删除@OneToMany
关系时,它运行完美
产品.java
@Entity
@Table(name="products")
public class Product implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name="SEQ_PRODUCTS", sequenceName="PRODUCTS_SEQ", allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_PRODUCTS")
private Long id;
@NotEmpty
@Column(name="NAME", nullable=false)
private String name;
@ManyToMany
private List<ProductImages> productImages;
@OneToMany(mappedBy="product",targetEntity=ProductReview.class,fetch = FetchType.EAGER,cascade = CascadeType.ALL)
private List <ProductReview> productReviews;
..... Getter and setter of above fields
}
ProductReview.class
@Entity
public class ProductReview implements Serializable {
private static final long serialVersionUID = 1L;
@GeneratedValue(strategy=GenerationType.AUTO)
@Id
private Long id;
private String title;
private String message;
private Double rating;
@ManyToOne
private Product product;
..... Getter and setter
}
API : http:// localhost:8080 / api / products
响应 :字符串错误
在您的ProductReview实体上,将@JoinColumn批注添加到“产品”字段中
@Entity
public class ProductReview implements Serializable {
....
@ManyToOne
@JoinColumn(name="product_id")
private Product product;
..... Getter and setter
}
我同意@Sivakumar的回答以及@varren的评论
当您使用一对多并且必须将关系放到一边时,请使用@JoinColumn(name="product_id")
和@ManyToOne
。 但是最好的办法是不要同时使用它,因为您并不总是需要它。
其次,由于这种循环参考
产品->产品参考和产品参考->产品
杰克逊串行器陷入无限循环。 因此,要避免这种情况,可以使用@JsonIgnore
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.