系统相关
首页 > 系统相关> > 使用Spring和Hibernate在内存db中使用DbUnit H2

使用Spring和Hibernate在内存db中使用DbUnit H2

作者:互联网

嗨,我正在尝试使用JPA和单元测试进行一点POC来验证是否已创建数据库模式.我正在使用H2 DB并且我设置为Hibernate从实体创建模式,但是当DbUnit尝试从数据集初始化DB时,我总是得到一个表…在tableMap中找不到.我读到我必须将属性DB_CLOSE_DELAY = -1添加到DB URL,但就像Hibernate创建模式一样,当DbUnit尝试初始化时DB丢失了.

有任何想法吗?任何帮助都非常感谢.

这是我的配置:

应用程序的context.xml

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSourceH2" />
    <property name="packagesToScan" value="com.xxx.model" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="generateDdl" value="true" />
            <property name="showSql" value="true" />
            <!-- property name="databasePlatform" value="org.hibernate.dialect.MySQLInnoDBDialect" /-->
            <property name="databasePlatform" value="org.hibernate.dialect.H2Dialect" />
            <!-- property name="database" value="MYSQL" /-->
        </bean>    
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <prop key="javax.persistence.validation.mode">CALLBACK</prop>
            </props>
        </property>
    </bean>

<bean id="dataSourceH2"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.h2.Driver" />
        <property name="url" value="jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>

RepositoryTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/application-context-test.xml" })
@Transactional
public class SystemEntityRepositoryH2Test {

    @Inject
    private SystemEntityRepository repository;

    @Inject
    private DataSource dataSourceH2;

    private IDatabaseConnection connection;

    @Before
    public void setUp() throws Exception {
        IDatabaseConnection dbUnitCon = null;
        dbUnitCon = new DatabaseDataSourceConnection(dataSourceH2, "testdb");
        dbUnitCon.getConfig().setProperty(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, true);

        IDataSet dataSet = this.getDataSet("dataset-systementity.xml");
        DatabaseOperation.INSERT.execute(dbUnitCon, dataSet);

    }

    @After
    public void tearDown() throws Exception {
        //DatabaseOperation.DELETE_ALL.execute(this.getConnection(), this.getDataSet(dataSetFile));
    }

    @Test
    public void test() throws Exception {

    }

    protected IDataSet getDataSet(String dataSetFile) throws Exception {
        ResourceLoader resourceLoader = new ClassRelativeResourceLoader(this.getClass());
        Resource resource = resourceLoader.getResource(dataSetFile);

        if (resource.exists()) {
            return new FlatXmlDataSetBuilder().build(resource.getInputStream());
        }

        return null;
    }
}

数据集,systementity.xml

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <System_Entities id="2" name="NAME" phone01="+52-55-55555555" email="a@a.com"
                    address01="Street" address02="123" address03="1" address04="Address04"
                    address05="Address05" city="City" state="State" country="MX"
                    zipcode="12345" />
</dataset>

错误

ERROR DatabaseDataSet:286 - Table 'System_Entities' not found in tableMap=org.dbunit.dataset.OrderedTableNameMap[_tableNames=[], _tableMap={}, _caseSensitiveTableNames=false]

我可以看到这些表是由hibernate创建的,因为日志显示所有sql语句而没有错误.

谢谢.

谢谢Mark Robinson
我将setUp方法修改为:

@Before
    public void setUp() throws Exception {
        IDatabaseConnection dbUnitCon = null;
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        Session session = entityManager.unwrap(Session.class);
        SessionImplementor si = (SessionImplementor) session;
        Connection conn = si.getJdbcConnectionAccess().obtainConnection();
        dbUnitCon = new DatabaseConnection(conn);

        //dbUnitCon.getConfig().setProperty(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, true);

        IDataSet dataSet = this.getDataSet("dataset-systementity.xml");
        DatabaseOperation.INSERT.execute(dbUnitCon, dataSet);
    }

它现在有效,我还不明白的是,如果我使用HSQLDB,我没有这个问题.

解决方法:

问题是DBUnit在Hibernate初始化之前加载表数据.

作为@setup的一部分,您需要获得Hibernate会话.这应该会导致Hibernate创建你的表.你甚至可以通过执行像select 1这样的简单查询来强制它

标签:unit-testing,spring,hibernate,h2,dbunit
来源: https://codeday.me/bug/20190624/1282920.html