简体   繁体   中英

Escaping reserved database keywords with spring-test-dbunit

How do I escape SQL Server keywords using Spring-test-dbunit framework ?

In my @DatabaseSetup("sampleData.xml") file, I have a table called File which is a reserved keyword in SQL Server. In order for the queries to run successfully on SQL Server, the reserved keyword would need to be encapsulated with square brackets ( [File] ).

From Expoting Dataset to a xml file giving error in DBunit , I see that this can be done in dbunit by setting a pattern escape config. I don't know where or how to put this config when using Spring-test-dbunit.

Where/how do I tell the spring-test-dbunit framework to properly escape database keywords when inserting the test data into the db using the provided xml feed?

If you would like to see code, let me know what excerpts I should post and i would be happy to do so.

I think, this might help you

public class DatabaseExport
{
    public static void main(String[] args) throws Exception
    {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
        Connection jdbcConn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=def_config","dbuser","dbpasswd");
        IDatabaseConnection iconn = new DatabaseConnection( jdbcConn );
        iconn.getConfig().setProperty(DatabaseConfig.PROPERTY_ESCAPE_PATTERN , "[?]");
        IDataSet fullDataSet = iconn.createDataSet();
        FlatXmlDataSet.write(fullDataSet, new FileOutputStream("X:/fullDataSet.xml"));
    }
}

To do this with spring-test-dbunit, you need to follow the "Custom IDatabaseConnections" section at their documentation page: https://springtestdbunit.github.io/spring-test-dbunit/

For the Java Config variant (and as a backup reference), see the answers of this StackOverflow question: Spring Test DBunit Warning

In your case, using the dbUnitDatabaseConfig bean, set the escapePattern property to "[?]" . As in:

<bean id="dbUnitDatabaseConfig" class="com.github.springtestdbunit.bean.DatabaseConfigBean">
    <property name="escapePattern" value="[?]"/>
</bean>

Side note, if JPA/Hibernate is used to generate the unit test schema at test-runtime, escaping for Hibernate is needed as well. Refer to this answer for that: https://stackoverflow.com/a/3463189/1034436

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM