Reputation: 27
I'm trying to make simple one to many relationship but hibernate is throwing error, no idea what to do.
Class Product:
public class Products {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne()
@JoinColumn(name = "user_id", foreignKey = @ForeignKey(name = "fk_user"))
private Users users;
}
and Class Users:
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;
@OneToMany()
@JoinColumn(name = "product_id", foreignKey = @ForeignKey(name = "fk_product_id"))
private List<Products> productsList = new ArrayList<>();
}
I got error: Error executing DDL "alter table products drop constraint fk_user" via JDBC Statement
Upvotes: 0
Views: 695
Reputation: 26076
Since the foreign key is on the child side (Products
class), you can drop it on the parent side and reference to child as being the owning side:
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;
@OneToMany(mappedBy="users")
private List<Products> productsList = new ArrayList<>();
}
Upvotes: 1
Reputation: 2255
Here is a working example of such relationship :
Drawer class :
@OneToMany (mappedBy="drawer", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)
private Set<Pocket> pockets;
Pocket class :
@ManyToOne (fetch=FetchType.EAGER)
@JoinColumn(name = "id_drawer", nullable = false)
private Drawer drawer;
Upvotes: 2