I try to implement the same problem as mentioned here some years ago: Hibernate many to many with a composite key with one field shared on either side of the relationship
I have a Menu and an Item class and want to implement a unidirectional relation that a menu saves all the items it contains.
Menu and Item both have composite keys out of the merchant_id foreign key and an auto incremental itemId/menuId. (EER Diagram Image)
Because Hibernate can not retrieve the auto generated Id when I declare a composite key and the Id is unique in the system, I save the entities without an extra embeddedId PKClass:
@Entity
@Table(name="ITEM")
public class Item extends AbstractTimestampEntity{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="itemId", nullable=false)
private long itemId;
@ManyToOne
@JoinColumn(name="merchantId", nullable=false)
private Merchant merchant;
@Column(name="name", length=45)
private String name;
@Column(name="description" , length=200)
private String description;
@Column(name="price")
private double price;
public Item(){} // getters & setters
@Entity
@Table(name="MENU")
public class Menu {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="menuId", nullable=false)
private long menuId;
@ManyToOne
@JoinColumn(name="merchantId", nullable=false)
private Merchant merchant;
@Column(name="name", length=45)
private String name;
@ManyToMany
@JoinTable(name="MENU_ITEM", joinColumns = {
@JoinColumn(name="menuId", nullable=false, updatable=false)},
//@JoinColumn(name="merchant.merchantId", nullable=false, updatable=false)},
inverseJoinColumns = { @JoinColumn(name="itemId", nullable=false, updatable=false)})
// @JoinColumn(name="merchantId", nullable=false, updatable=false)})
private List<Item> items = new ArrayList<Item>(); // constructor, getters & setters
As you can see from the commented code, here is the point were my question comes in. How do I map the entities now the best without modifying my normalized database table? (They need to have the same merchant to be validated in the database)