2017-09-25 28 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; 
}