0
votes

I am using spring framework in my product class there is @OneToMany relationship between product and productReview So I mapped this relation as follows but when I called findAll() method of products it gives me an error of Bad String I cant figure out what is the problem , when I removed @OneToMany relation it runs perfectly

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

Response : Bad String

2
Try to add lazy loading feature. - Sandeep
@FirzaAhmed you should get exception in console if you need more info. But the main problem here is that you probably get some sort of recursive relations that Jackson cant resolve without additional helper info. So setup annotations or custom serializer. Another option is to remove one part of the relation that you will not use in your program, like there is no point to have List <ProductReview> productReviews, because you can always query ProductReview table if you need this info - varren

2 Answers

0
votes

On your ProductReview entity add @JoinColumn annotation to your Product field

@Entity
public class ProductReview implements Serializable {

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

I agree with answer from @Sivakumar and also the comment from @varren

When you use one to many and you have to put the relationship on both side then use the @JoinColumn(name="product_id") with @ManyToOne. But best idea is not to use it on both side because you don't always need it.

Secondly, because of this circular reference

Product -> ProductReference & ProductReference -> Product

The jackson serializer falls into infinite loop. So, to avoid this you can use @JsonIgnore.