2

I have the following mapping:

//...
@Table(name="A")
public class A{
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "A_B", joinColumns = {@JoinColumn(name = "A_ID")}, inverseJoinColumns = {@JoinColumn(name = "B_ID")})
    public Set<B> getBs() {
            return this.meals;
        }
    //...
}

//...
@Table(name="B")
public class B{
  private int id;
  private String description;
  //...
}  

How can specify the names of the foreign keys in table "A_B"? (FK_A_ID and FK_B_ID)

Thanks in advance, Neuquino

Neuquino
  • 11,580
  • 20
  • 62
  • 76

1 Answers1

2

You can use the @ForeignKey to specify the name of the foreign key constraint in the join table .

For example:

@ForeignKey(name="FK_A_ID" , inverseName="FK_B_ID")
@JoinTable(name = "A_B", joinColumns = {@JoinColumn(name = "A_ID")}, inverseJoinColumns = {@JoinColumn(name = "B_ID")})
public Set<B> getBs() {
      return this.meals;
}

Then Table A_B has the following structure:

  • A column called A_ID which has the foreign key constraint to the primary key of Table A .The name of this foreign key is FK_A_ID

  • A column called B_ID which has the foreign key constraint to the primary key of Table B.The name of this foreign key is FK_B_ID

Ken Chan
  • 84,777
  • 26
  • 143
  • 172
  • I want to change the name of the constraint, not the name of the column. For simple attributes I use @ForeignKey, but for a JoinTable I don't know how to do it. – Neuquino Apr 17 '12 at 20:01
  • 1
    @KenChan Do you have any idea how to do that in Hibernate 4.3, without deprecated org.hibernate.annotations.ForeignKey? – Piohen Oct 08 '14 at 10:26
  • Turns out that's a bug: https://hibernate.atlassian.net/browse/HHH-8862 (http://stackoverflow.com/questions/21103795/schema-generation-with-eclipselink-and-hibernate-jpa2-1-foreignkey-ignored) – Piohen Oct 08 '14 at 12:27