整合前的數(shù)據(jù)庫連接方式
??MyBatis的配置文件主要包括數(shù)據(jù)庫連接池配置文件、日志輸出配置文件和Mapper映射配置文件,其中主要配置信息在數(shù)據(jù)庫連接池配置文件,這里是SqlMapConfig.xml。
該文件通過<settings>標(biāo)簽來設(shè)置日志輸出模式。
通過<mappers>標(biāo)簽來配置Mapper映射配置文件的路徑。
??和傳統(tǒng)的JDBC相比,MyBatis將數(shù)據(jù)庫連接關(guān)閉、SQL語句的輸入輸出映射都放在配置文件中。不再需要通過getConnection()方法來獲取數(shù)據(jù)庫的連接。而是先通過Resources資源加載類加載SqlMapConfig.xml配置文件,然后以Resources對(duì)象為參數(shù),創(chuàng)建出會(huì)話工廠SqlSessionFactory。該工廠就可以創(chuàng)建出與數(shù)據(jù)庫交互的sqlSession類的實(shí)例對(duì)象。
public class DataConnection{
private String resource = "SqlMapConfig.xml";
private SqlSessionFactory SqlSessionFactory;
private SqlSession SqlSession;
public SqlSession getSqlSession() throws IOException{
InputStream inputStream =Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
}
??雖然不需要通過getConnection()方法獲取連接,但是需要通過新建DataConnection實(shí)例對(duì)象,并調(diào)用getSqlSession()方法來獲取連接。
??除了直接將數(shù)據(jù)庫連接信息放在SqlMapConfig.xml中以外,還可以采用類似的方法將配置信息放在properties格式的文件中。例如在SqlMapConfig.xml中引入:
<properties resource="org/mybatis/example/db.properties">
??然后將數(shù)據(jù)庫連接信息放在db.properties中。這時(shí)候當(dāng)然在SqlMapConfig.xml中還是有數(shù)據(jù)庫連接的內(nèi)容,但是具體的信息只需要通過“${}”來引用properties文件中的變量就可以了。這樣可以避免數(shù)據(jù)庫配置信息的硬編碼。
整合后的數(shù)據(jù)庫連接方式
?? Spring與MyBatis進(jìn)行整合。其中的一個(gè)好處就是能夠以單例方式來管理SqlSessionFactory。當(dāng)然這也就意味著通過Spring來創(chuàng)建SqlSessionFactory,替代了上面的DataConnection類的工作。
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<context:property-placeholder location="classpath:db.properties">
<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="maxActive" value="10"></property>
<property name="maxIdle" value="5"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="mybatis/SqlMapConfig.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
??這時(shí)候,MyBatis的全局配置文件SqlMapConfig.xml就不需要配置數(shù)據(jù)源信息了,只需要配置一些緩存的setting參數(shù)、以及typeAliases別名等。