<select id="selectPerson" parameterType="int" parameterMap="deprecated" resultType="hashmap" resultMap="personResultMap" flushCache="false" useCache="true" timeout="10000" fetchSize="256" statementType="PREPARED" resultSetType="FORWARD_ONLY" databaseId="mysql">
下面的解釋中有一個databaseId屬性: 如果配置了 databaseIdProvider,MyBatis 會加載所有的不帶 databaseId 或匹配當前 databaseId 的語句;如果帶或者不帶的語句都有,則不帶的會被忽略。新增,修改和刪除都有這個屬性
也就是說先匹配具有這個屬性的語句
一、在configuration.xml配置
<databaseIdProvider type="DB_VENDOR"> <property name="MySQL" value="mysql" /> <property name="Oracle" value="oracle" /> </databaseIdProvider>
二、新建Mapper
public interface DatabaseIdProviderMapper {
String selectTime();
}
三、新建 DatabaseIdProvider.xml
<mapper namespace="com.yihaomen.mybatis.dao.DatabaseIdProviderMapper">
<select id="selectTime" resultType="String" databaseId="mysql">
SELECT NOW() FROM dual
</select>
<select id="selectTime" resultType="String" databaseId="oracle">
SELECT 'oralce'||to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') FROM dual
</select>
</mapper>
四、在configuration.xml中添加映射器
<mappers>
<mapper resource="com/yihaomen/mybatis/model/DatabaseIdProvider.xml"/>
</mappers>
五、jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis-learn?characterEncoding=utf8 jdbc.username=root jdbc.password=tiger #jdbc.driver=oracle.jdbc.driver.OracleDriver #jdbc.url=jdbc:oracle:thin:@localhost:1521:mybatis #jdbc.username=mybatis #jdbc.password=mybatis maxActive= 50
六、測試
import com.yihaomen.mybatis.dao.DatabaseIdProviderMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import user.BaseTest;
public class DatabaseIdProviderTest extends BaseTest{
public static void main(String[] args) {
SqlSessionFactory factory = getSession();
SqlSession session = factory.openSession();
DatabaseIdProviderMapper mapper = session.getMapper(DatabaseIdProviderMapper.class);
System.out.println(mapper.selectTime());
}
}
- 結果說明
如果當前啟用的是oracle則執行databaseId=”oracle”的語句,如果mysql值執行databaseId=”mysql”的語句 - 在做測試的時候很有可能,你沒有加入其它的數據庫測試環境那么很有可能你會出現 ### Error querying database.,你需要移除不存在的環境即可

