由於原生態的JDBC編程存在硬編碼問題,維護不方便於是mybatis等持久層框架應運而生。
mybatis開發dao層有兩種方法
(1)開發dao接口及其實現類
(2)mapper代理開發。它是對(1)的優化與發展。
下面只介紹mapper代理開發。先剖析一下原理。
mapper的代理實現類是由org.mybatis.spring.mapper.MapperScannerConfigurer生成的,並且依賴於org.mybatis.spring.SqlSessionFactoryBean對象。
而sqlSessionFactory對象又依賴“數據源”和“mybatis配置文件(或者是XXXmapper.xml的路徑)”。
所以我們只需要配置好“數據源”、“sqlSessionFactory”、“或者是XXXmapper.xml的路徑”三處即可,當然也需要遵循mapper代理開發的一些規範。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<context:property-placeholder location="classpath:config/db.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc_driverClassName}" />
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath:cn/tqs/easyui/mapper/*.xml"></property>
<property name="dataSource" ref="dataSource" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.tqs.easyui.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>