How to stop Spring boot Jpa from adding foreign key constraints to the database views on the startup?

Viewed 40

In my Spring boot web application there are several views that define as entity model. In the startup of this application, many exceptions are thrown like below:

GenerationTarget encountered exception accepting command : Error executing DDL "alter table view_staff add constraint FK7qgsdfanumdw1ji68 foreign key (type_id) references stafftype" via JDBC Statement

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table view_staff add constraint FK7qgsdfanumdw1ji68 foreign key (type_id) references stafftype" via JDBC Statement
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:581) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:526) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applyForeignKeys(AbstractSchemaMigrator.java:452) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:263) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:123) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:196) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:85) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:335) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]

This is one of my view models:

@Data
@Entity
@Table(name = "view_staff")
public class ViewStaff  {
    @Id
    private Long id;
    private String title;
    private String description;
    @ManyToOne(optional = false)
    private StaffType Type;
}

How I could prevent spring boot from adding foreign key constraints to those views?

1 Answers

Because you dont tell Spring what is the the id to join the column to, it creates one default of its own that does not exists:

(type_id) references stafftype

Add:

@ManyToOne(optional = false)
@JoinColumn(name="staffType_id", nullable=false)
private StaffType staffType;

Make sure you have the completeing code on StaffType:

@OneToMany(mappedBy="staffType")
private Set<ViewStaff> ViewStaffs;

Check out this for more info

Related