【发布时间】:2020-03-25 02:39:38
【问题描述】:
我有一个映射到数据库视图的实体,例如
@Entity
@Immutable
@Table(name = "my_view")
public class MyView {
// some properties and getters
}
而我的sql挂件就像create view my_view as select * from thisAndThat and stupid logic;
在我的生产环境中,它就像一个魅力。
现在在我的集成测试中,我使用 Hibernate 属性 hibernate.hbm2ddl.auto = update 在 HSQL 中使用 DbUnit 动态创建我的数据库设置。因为我没有将实体表标记为视图,直接hibernate尝试创建数据库。
我可以通过使用 flyway 并添加迁移脚本来解决此问题
drop table if exists my_view;
create view my_view AS ....;
首先:它有效
但是:在构建我的项目时,我遇到了很多异常
2019-11-29 14:03:43,023 WARN ExceptionHandlerLoggedImpl:handleException:27 GenerationTarget encountered exception accepting command : Error executing DDL "alter table my_view add constraint FKj50dxtl46l99jfi90uf4df7vo foreign key (other_table_id) references fonds" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table my_view add constraint FKj50dxtl46l99jfi90uf4df7vo foreign key (other_table_id) references other_table" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applyForeignKeys(AbstractSchemaMigrator.java:433)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:249)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:315)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:615)
....
这a)有点令人不安,b)让我很紧张,这可能会在(不久的)将来发生。
你知道我如何可以跳过使用hibernate.hbm2ddl.auto 创建特定的表格吗?
提前致谢!
【问题讨论】:
-
你能做到吗?如果是这样,您是如何设置 dbUnit 数据集来为视图提供数据的?我尝试像普通表一样包含它并最终出现 org.dbunit.dataset.NoSuchTableException 错误。
-
作为接受的答案建议我使用注释 \@Subselect("Select * from my_view")。这就是诀窍。仅供参考,我还使用注释 \@Entity 和 \@Immutable
-
我做同样的事情。如果您查看数据库日志,hibernate 是否在部署过程中创建了一个“my_view”表?如果你清除hibernate创建的.script,它有什么不同吗?我遇到的一个问题是,该脚本最初包含一个表的创建查询,在我将其更改为视图之前,所以一切“似乎”都在工作。但是,一旦我删除了脚本,就不再添加视图,因此 dbunit 找不到要填充的表。
-
hibernate 不会自动创建任何表/视图。我添加了一个初始化脚本并在编译和测试执行之间手动创建视图
标签: java spring hibernate view hbm2ddl