春季启动应用程序

时间:2017-10-31 06:59:59

标签: java spring one-to-many entity-relationship

我在我的产品类中使用spring框架@OneToManyproduct之间存在productReview关系所以我将此关系映射如下,但是当我调用findAll()方法时它给我一个错误Bad String 我无法弄清问题是什么,当我删除@OneToMany关系时,它运行得很好

Product.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

响应:错误字符串

2 个答案:

答案 0 :(得分:0)

在ProductReview实体上,将@JoinColumn注释添加到“产品”字段

@Entity
public class ProductReview implements Serializable {

....
@ManyToOne
@JoinColumn(name="product_id")
private Product product;
..... Getter and setter
}

答案 1 :(得分:0)

我同意@Sivakumar的回答以及@varren的评论

当您使用一对多,并且您必须将关系放在两边时,请使用@JoinColumn(name="product_id")@ManyToOne。但最好的想法是不要在两边都使用它,因为你并不总是需要它。

其次,因为这个循环引用

  

产品 - &gt; ProductReference&amp; ProductReference - &gt;产品

杰克逊序列化器陷入无限循环。因此,为了避免这种情况,您可以使用@JsonIgnore