Home > Enterprise >  Hibernate adds unwanted unique key itself In @OneToMany mapping
Hibernate adds unwanted unique key itself In @OneToMany mapping

Time:09-25

I have 3 entities in my Spring boot application. User,Item and Orders I want one Orders object to have multiple Items so, I used @OneToMany mapping in Orders class.

This is my code:

This is my Item.java file

@Entity
public class Item implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="item_id")
private int itemId;
@Column
private String name;
@Column
private int price;
@Column
private String image;
@Column(name = "item_user_id")
private int userId;

//getters ssetters

}

This is my Orders.java file

@Entity
public class Orders implements Serializable {

private static final long serialVersionUID = 3L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "order_id")
private int orderId;

@Column(name = "order_user_id")
private int userId;

@Column
@OneToMany
private List<Item> items = new ArrayList<>();

//getters setters

}

Hibernate is generating 3 tables as I expected Item , Orders and Orders_Item from above code.

Orders table has two columns order_id and order_user_id

Also Orders_Item table has two columns orders_order_id and items_item_id

hibernate is making items_item_id a unique key, I don't want this

Hibernate: alter table orders_items add constraint UK_9uu7j0okufkkanam94v8gb2qa unique (items_item_id)

SO MY ISSUE IS I CAN'T INSERT AN ITEM HAVING ONE ID MORE THAN ONCE

How can this issue be ressolved?

CodePudding user response:

Try specifying your items_item_id to have Not Null constraint in your database.

Like:

items_item_id int Not null

I hope this will solve your problem..

CodePudding user response:

If you want to remove the unique constraint on items_item_id then you have a ManyToMany relationship, you want to associate an item to more than one order. Change your @OneToMany annotation to a @ManyToMany annotation.

  • Related