JPA OneToMany column name
Asked Answered
A

1

6

How to set the column name of the foreign key when setting up a one-to-many relationship in JPA?

I would like to change the name of "items_id" to "item_id"

@OneToMany
private List<Item> items;

I tried the following annotations with no success:

  1. @JoinColumn(name="item_id") // join table is not created
  2. @Column(name="item_id") // no effect
Arlenearles answered 6/4, 2018 at 20:3 Comment(1)
You want to customize the join table used to map the association. The annotation to do that is... JoinTable. docs.oracle.com/javaee/7/api/javax/persistence/JoinTable.htmlMillimeter
G
8

You want to override the mappings of the default values of the join table, so the @JoinTable annotation is the one to use. You want to override the name of the inverseJoinColumn from items_id to item_id:

    @OneToMany
    @JoinTable(inverseJoinColumns=@JoinColumn(name="item_id"))
    List<Item> items;

@OneToMany and @JoinColumn makes a different mapping, a join table is not created and a foreign key is created in the referenced entity table(in the Item table in your case).

@Column is used to override the names for entity attributes, not for relationships.

Grosvenor answered 6/4, 2018 at 21:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.