databaseIdProvider

MyBatis is able to execute different statements depending on your database vendor. The multi-db vendor support is based on the mapped statements databaseId attribute. MyBatis will load all statements with no databaseId attribute or with a databaseId that matches the current one. In case the same statement is found with and without the databaseId the latter will be discarded. To enable the multi vendor support add a databaseIdProvider to mybatis-config.xml file as follows:

  1. <databaseIdProvider type="DB_VENDOR" />

The DB_VENDOR implementation databaseIdProvider sets as databaseId the String returned by DatabaseMetaData#getDatabaseProductName(). Given that usually that string is too long and that different versions of the same product may return different values, you may want to convert it to a shorter one by adding properties like follows:

  1. <databaseIdProvider type="DB_VENDOR">
  2. <property name="SQL Server" value="sqlserver"/>
  3. <property name="DB2" value="db2"/>
  4. <property name="Oracle" value="oracle" />
  5. </databaseIdProvider>

When properties are provided, the DB_VENDOR databaseIdProvider will search the property value corresponding to the first key found in the returned database product name or “null” if there is not a matching property. In this case, if getDatabaseProductName() returns “Oracle (DataDirect)” the databaseId will be set to “oracle”.

You can build your own DatabaseIdProvider by implementing the interface org.apache.ibatis.mapping.DatabaseIdProvider and registering it in mybatis-config.xml:

  1. public interface DatabaseIdProvider {
  2. default void setProperties(Properties p) { // Since 3.5.2, changed to default method
  3. // NOP
  4. }
  5. String getDatabaseId(DataSource dataSource) throws SQLException;
  6. }