Search code examples
javahibernatejpaone-to-manymany-to-one

Value null in all relations ManyToOne with hibernate


I want to establish a 1 to N relationship between the product and the supplier, so that a supplier can offer several products, but a product has only one supplier. I have used the corresponding JPA annotations but the correct relationship is still not established. Getting in all my relationships 1 to N, as value entered null. What is happening?

Product.java

@Entity
@Table(name="PRODUCTS")
public class Product implements Serializable{
    
    private static final long serialVersionUID = 1L;

    @Id //@GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;
    private String name;
    private String unit;
    private double price;
    private boolean available;
        
    @ManyToOne (cascade = {     
            CascadeType.DETACH,
            CascadeType.MERGE,
            CascadeType.PERSIST,
            CascadeType.REFRESH
    })
    @JoinColumn(insertable=false, updatable=false)
    private Supplier supplier;

    @OneToMany(mappedBy = "product", fetch = FetchType.EAGER, cascade = {       
            CascadeType.DETACH,
            CascadeType.MERGE,
            CascadeType.PERSIST,
            CascadeType.REFRESH
    })
    private List<OrderDetail> orderDetails;
    
    @ManyToMany
    @JoinColumn(insertable=false, updatable=false)
    private List<Category> categories;
    
    @ManyToMany(mappedBy = "cart", fetch = FetchType.EAGER, cascade = {     
            CascadeType.DETACH,
            CascadeType.MERGE,
            CascadeType.PERSIST,
            CascadeType.REFRESH
    })
    private List<Client> customers;

Supplier.java

@Entity
@Table(name="SUPPLIERS")
public class Supplier implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id //@GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;
    private String name;
    private String contactName;
    private String email;
    private String password;
    private String phone;
    private String country;
    private String city;
    private String address;
    private String postalCode;
    
    @OneToMany(mappedBy="supplier", fetch = FetchType.EAGER, cascade = {
            CascadeType.DETACH,
            CascadeType.MERGE,
            CascadeType.PERSIST,
            CascadeType.REFRESH
    })
    private List<Product> suppliedProducts;

Solution

  • I've solved substituting @JoinColumn(insertable=false, updatable=false) from false to true. This change allow hibernate to insert and update the wanted value.