我有一个 Spring/Hibernate webapp,它有一些在内存 HSQL 数据库上运行的集成测试。由于 hbm2ddl=create,Hibernate 使用这个空白数据库并创建我所有的测试表和约束。但是,我有一个新 bean,它在 afterPropertiesSet() 方法期间检查数据库中的特定配置值,因此当初始化这个 bean 时,数据库中需要存在这样的行。
有没有什么好的方法来设置一个 Java/Spring/Hibernate 等价于 Rail 的测试装置?我正在尝试找到一种方法来告诉 Hibernate“无论何时创建此表,然后立即插入这些行”。我找不到可以添加的回调或 Hook ,但也许还有其他方法。
最佳答案
I'm trying to find a way to tell Hibernate "whenever you create this table, insert these rows immediately afterwards"
从 Hibernate 3.1 开始,您可以在 Hibernate 的运行时类路径中包含一个名为 import.sql
的文件,并且在模式导出时,Hibernate 将在模式之后执行该文件中包含的 SQL 语句已导出。
此功能已在 Rotterdam JBug and Hibernate's import.sql 中公布。博文:
import.sql: easily import data in your unit tests
Hibernate has a neat little feature that is heavily under-documented and unknown. You can execute an SQL script during the
SessionFactory
creation right after the database schema generation to import data in a fresh database. You just need to add a file namedimport.sql
in your classpath root and set eithercreate
orcreate-drop
as yourhibernate.hbm2ddl.auto
property.I use it for Hibernate Search in Action now that I have started the query chapter. It initializes my database with a fresh set of data for my unit tests. JBoss Seam also uses it a lot in the various examples.
import.sql
is a very simple feature but is quite useful at time. Remember that the SQL might be dependent on your database (ah portability!).#import.sql file delete from PRODUCTS insert into PRODUCTS (PROD_ID, ASIN, TITLE, PRICE, IMAGE_URL, DESCRIPTION) values ('1', '630522577X', 'My Fair Lady', 19.98, '630522577X.jpg', 'My Fair blah blah...'); insert into PRODUCTS (PROD_ID, ASIN, TITLE, PRICE, IMAGE_URL, DESCRIPTION) values ('2', 'B00003CXCD', 'Roman Holiday ', 12.98, 'B00003CXCD.jpg', 'We could argue that blah blah');
For more information about this feature, check Eyal's blog, he wrote a nice little entry about it. Remember if you want to add additional database objects (indexes, tables and so on), you can also use the auxiliary database objects feature.
它仍然没有真正记录下来。
关于java - Spring/Hibernate 测试 : Inserting test data after DDL creation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3408991/