简体   繁体   中英

Hibernate OnetoMany and ManyToOne throw exception

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

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;

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<>();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM