Home > Enterprise >  JPA/ManyToOne/JoinColumn with a database View : how to avoid Foreign Key generation?
JPA/ManyToOne/JoinColumn with a database View : how to avoid Foreign Key generation?

Time:09-29

I have a @ManyToOne association, the target entity maps a database view. JPA/Hibernate tries to generate a Foreign Key constraint between the table and the view, which is not possible (so I get an exception at each start of application). How to avoid this ?

@Entity
public class ThirdParty{
  @Id
  String id=UUID.randomUUID().toString();

  String bookId;

  @ManyToOne(fetch = FetchType.LAZY)
  @MapsId("bookId")
  @JoinColumn(name="bookId", referencedColumnName = "cid", foreignKey = @ForeignKey(name = "none"))
  private XCompany xCompany;

  //...
}

I get this exception :

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL

Caused by: java.sql.SQLException: (conn=1266699) Cannot add foreign key constraint

Putting foreignKey = @ForeignKey(name = "none") has no effect.

Any idea ?

CodePudding user response:

The naming used for the foreign key can be reserved words. Did you check this? For example; The word 'none' is a reserved word for MySQL.

CodePudding user response:

Instead of using the name none, use @ForeignKey(ConstraintMode.NO_CONSTRAINT)

  • Related