Forece85
Forece85

Reputation: 518

Spring Data JPA - Hibernate - OneToMany, ManytoOne bidirectional

Have 2 Entities: Orders and Products. 1 Order can have Many Products and Many Products can belong to 1 Order (Each Product only belongs to 1 Order).

With unidirectional association at Order Entity, I am able to retrieve product details when performing orderRepo.findAll(); In similar fashion, need order details when performing productRepo.findAll();

Tried code:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "order_details")
public class OrderData {

    @Id
    @Column(name = "order_id", nullable = false, unique = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long orderId;

    @NotNull
    @Column(name = "customer_name", nullable = false)
    private String customerName;

    @OneToMany(mappedBy = "productId", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<ProductData> products;

}

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "product_details")
public class ProductData {

    @Id
    @Column(name = "product_id", nullable = false, unique = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long productId;

    @NotNull
    @Column(name = "product_name", nullable = false)
    private String productName;

    @ManyToOne(fetch = FetchType.LAZY, optional = false, cascade = CascadeType.ALL)
    @JoinColumn(name = "order_id", nullable = false)
    private OrderData orderData;
}

While inserting at products; we are getting error: "insert or update on table violates foreign key constraint jpa"

While performing productRep.findAll(): infinite loop for hibernate select queries

Tried @JsonIgnore. This not returning child or parent elements. Tried @JsonManagedReference vs @JsonBackReference - still no luck.

Please guide me on this

Upvotes: 0

Views: 323

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36223

The mappedBy attribute points to the wrong field:

@OneToMany(mappedBy = "productId", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<ProductData> products;

This must be the back reference:

@OneToMany(mappedBy = "orderData", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<ProductData> products;

Upvotes: 1

Related Questions