Spring boot – ‘One To Many’ attribute value type should not be Error

Total
1
Shares

I have my api in Spring Boot.

I have 2 classes:

Here is my Supplier Class:

 public class Supplier{
     @OneToMany(cascade= {CascadeType.ALL})
     private List<Product> products;      <---  This one is working perfectly fine.

     @OneToMany(cascade= {CascadeType.ALL})
     private List<Ingredient> components;      <---- this is the line where I am getting an error

}

Here is the error message that I am getting:

‘One To Many’ attribute value type should not be ‘Ingredient’

Here is my Ingredient class

public class Ingredient {

     @Id
     @GeneratedValue
     private Long id;
     private String name;
     private String unit;
     private Double quantity = 0.0;
     private Double cost = 0.0;
     private Double price = 0.0;
}

My Question:
What is a possible fix to the above error in:

private List<Ingredient> components;

Even though the line above it is working ?


Solution

If you have a unidirectional association @OneToMany you need to replace

@OneToMany(cascade= {CascadeType.ALL})
private List<Ingredient> components; 

to

@OneToMany(cascade= {CascadeType.ALL})  
@JoinColumn(name="components")
private List<Ingredient> components; 

If you want a bidirectional association @OneToMany you have to add in your Ingredient class

...
@ManyToOne
@JoinColumn
private Supplier supplier;

and the supplier class nothing changes
links to help you understand

https://javabydeveloper.com/one-many-unidirectional-association/

https://javabydeveloper.com/one-to-many-bidirectional-association/

Let me know if that helped!

Leave a Reply

Your email address will not be published. Required fields are marked *