I have a class User which has a parameter of another class type ShoppingList. As this…
@Entity public class Employee implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(nullable = false, updatable = false) private Long id; private String Name; @????? private ShoppingList[] shoppingList; }
How can i make this ManyToOne relationship while the variable being an array? The idea is to have a User table and another ShoppingList table, so the user can have multiple lists at the same time.
Advertisement
Answer
This would be the correct way:
One Employee
has many ShoppingList
s.
One ShoppingList
has only one Employee
.
@Entity public class Employee implements Serializable { .... @OneToMany(mappedBy = "employee", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<ShoppingList> shoppingList; .... }
@Entity public class ShoppingList implements Serializable { .... @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "employee_id", nullable = false) private Employee employee; .... }
You can fine-tune your entities as per your need. For more info, I would refer to this tutorial, it has helped me a lot.