Issue
This Content is from Stack Overflow. Question asked by MTB
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]
How I could prevent spring boot from adding foreign key constraints to those views?
Solution
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
This Question was asked in StackOverflow by MTB and Answered by Stempler It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.