2017-09-25 68 views
0

我在MS SQL Server中有一个用户定义的函数,它从Java代码调用,在H2数据库中运行集成测试时显示为未定义。你可以在the previous question找到我的代码。DbUnit - JdbcSQLException:函数“*”未找到

测试代码:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = {H2Config.class}) 
@TestExecutionListeners({ 
     DependencyInjectionTestExecutionListener.class, 
     DbUnitTestExecutionListener.class, 
     TransactionalTestExecutionListener.class 
}) 
@TransactionConfiguration(defaultRollback = true) 
public class TableDaoTest { 

    @Autowired 
    private TableDao tableDao; 

    @Test 
    @DatabaseSetup("/datasets/import.xml") 
    public void testMethod01() { 
     tableDao.getRecordsByGroup(); 
     ... 

数据库模式是由Hibernate来自动生成。正如你可以看到测试数据由DbUnit使用xml数据集填充。并且此测试失败,因为我的函数存在于MS SQL服务器数据库中是H2数据库中未定义的。

应用程序日志:

Caused by: org.hibernate.exception.GenericJDBCException: could not prepare statement 
    ... 
Caused by: org.h2.jdbc.JdbcSQLException: Function "SAFE_MOD" not found; SQL statement: 
    select table10_.id, table10_.value, ... from Table1 table10_ where table10_.group1=dbo.safe_mod(?, ?); 
    ... 

如何导入/创建DbUnit的测试前的功能?

回答

0

H2数据库不支持用户定义的SQL函数。但是,在这个数据库中,Java函数也可以用作存储过程。

@SuppressWarnings("unused") 
public class H2Function { 
    public static int safeMod(Integer n, Integer divider) { 
     if (divider == null) { 
      divider = 5000; 
     } 

     return n % divider; 
    } 

} 

请注意,只支持静态Java方法;班级和方法都必须公开。

的Java函数必须声明(在数据库中注册),通过调用CREATE ALIAS ... FOR之前,它可用于:

CREATE ALIAS IF NOT EXISTS safe_mod DETERMINISTIC FOR "by.naxa.H2Function.safeMod"; 

这种说法应该任何测试之前进行,所以我决定把它连接初始SQL内:

@Bean 
public DataSource dataSource() { 
    BasicDataSource dataSource = new BasicDataSource(); 

    dataSource.setDriverClassName("org.h2.Driver"); 
    dataSource.setUrl("jdbc:h2:mem:my_db_name"); 
    dataSource.setUsername("sa"); 
    dataSource.setPassword(""); 
    dataSource.setConnectionInitSqls(Collections.singleton(
     "CREATE ALIAS IF NOT EXISTS safe_mod DETERMINISTIC FOR \"by.naxa.H2Function.safeMod\";")); 

    return dataSource; 
}