Spring-Mybatis --- 配置SqlSessionFactoryBean,整合Spring-Mybatis(轉)
要利用Mybatis首先是需要導入mybatis-x.x.x.jar,其次,要整合Spring和Mybatis需要導入mybatis-spring-x.x.x.jar。
JAR : mybatis-x.x.x
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.6</version> </dependency>
JAR : mybatis-spring-x.x.x
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency>
1、Spring整合Mybatis的xml配置
xml : POM
<!-- DB --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-servlet-api</artifactId> <version>7.0.54</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> <version>7.0.23</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.18</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.6</version> </dependency>
xml : DataSource
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close"> <property name="poolProperties"> <bean class="org.apache.tomcat.jdbc.pool.PoolProperties"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.user}" /> <property name="password" value="${jdbc.password}" /> <!-- Register the pool with JMX. In order for the connection pool object to create the MBean. --> <property name="jmxEnabled" value="true" /> <!-- The indication of whether objects will be validated by the idle object evictor. --> <property name="testWhileIdle" value="true" /> <!-- The indication of whether objects will be validated before being borrowed from the pool. --> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="initialSize" value="${jdbc.initialPoolSize}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxWait" value="${jdbc.maxWait}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="maxIdle" value="${jdbc.maxIdle}" /> <property name="maxAge" value="60000" /> <!-- The number of milliseconds to sleep between runs of the idle connection validation/cleaner thread. --> <property name="timeBetweenEvictionRunsMillis" value="15000" /> <!-- The minimum amount of time an object may sit idle in the pool before it is eligible for eviction. --> <property name="minEvictableIdleTimeMillis" value="60000" /> <property name="removeAbandoned" value="true" /> <property name="removeAbandonedTimeout" value="30" /> <property name="validationQuery" value="SELECT 1" /> <property name="validationInterval" value="30000" /> </bean> </property> </bean>
常用配置:
(如果在mybatis-config.xml利用<mappers>進行xml映射文件的配置,就可以不用配置下面的mapperLocation屬性了)
<!-- mybatis文件配置,掃描所有mapper文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis-config.xml" p:mapperLocations="classpath:com/eliteams/quick4j/web/dao/*.xml"/> <!-- spring與mybatis整合配置,掃描所有dao,在單數據源的情況下可以不寫sqlSessionFactoryBeanName --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.eliteams.quick4j.web.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
-------------------------阿彌陀佛----佛祖保佑----永無BUG--------------------------
2、Spring和Mybatis整合的三種方式
一
-
SqlSessionFactoryBean來替代SqlSessionFactoryBuilder來創建SqlSession
-
利用mybatis映射文件**.xml來配置
SqlSessionFactoryBean有一個必須屬性dataSource,另外其還有一個通用屬性configLocation(用來指定mybatis的xml配置文件路徑)。
Spring的xml配置:
<!-- 創建SqlSessionFactory,同時指定數據源--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 指定sqlMapConfig總配置文件,訂制的environment在spring容器中不在生效--> <property name="configLocation" value="classpath:sqlMapConfig.xml"/> </bean>
mybatis總配置文件sqlMapConfig.xml:
<configuration> <typeAliases> <typeAlias type="com.xxt.ibatis.dbcp.domain.User" alias="User" /> </typeAliases> <mappers> <mapper resource="com/xxt/ibatis/dbcp/domain/userMapper.xml" /> </mappers> </configuration>
userMapper.xml:
<mapper namespace="com.xxt.ibatis.dbcp.dao.UserDao"> <resultMap type="User" id="userMap"> <id property="id" column="id" /> <result property="name" column="name" /> <result property="password" column="password" /> <result property="createTime" column="createtime" /> </resultMap> <select id="getUserById" parameterType="int" resultMap="userMap"> select * from user where id = #{id} </select> <mapper/>
DAO層接口類UserDao.java:註意此處定義的接口方法需要和UserMapper.xml映射的<select>標簽的id對應
public interface UserDao { public User getUserById(int id); }
需要操作數據時調用的類UserService.java:
public class UserService { //此處省略sqlSession的獲取方法 private SqlSession sqlSession; private UserDao userDao; public User getUserById(int id) { return userDao.getUserById(id); } }
二
-
SqlSessionFactoryBean來替代SqlSessionFactoryBuilder來創建SqlSession
-
采用數據映射器(MapperFactoryBean)的方式
-
不用寫mybatis映射文件
-
采用註解方式提供相應的sql語句和輸入參數。
Spring的xml配置:
<!-- 引入jdbc配置文件 --> <context:property-placeholder location="jdbc.properties"/> <!--創建jdbc數據源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <property name="initialSize" value="${initialSize}"/> <property name="maxActive" value="${maxActive}"/> <property name="maxIdle" value="${maxIdle}"/> <property name="minIdle" value="${minIdle}"/> </bean> <!-- 創建SqlSessionFactory,同時指定數據源--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!--創建數據映射器,數據映射器必須為接口--> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.xxt.ibatis.dbcp.dao.UserMapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> <bean id="userDaoImpl" class="com.xxt.ibatis.dbcp.dao.impl.UserDaoImpl"> <property name="userMapper" ref="userMapper"/> </bean>
數據映射器UserMapper.java:
public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{userId}") User getUser(@Param("userId") long id); }
DAO接口類UserDao.java:
public interface UserDao { public User getUserById(User user); }
DAO接口實現類UserDaoImpl.java:
public class UserDaoImpl implements UserDao { private UserMapper userMapper; public void setUserMapper(UserMapper userMapper) { this.userMapper = userMapper; } public User getUserById(User user) { return userMapper.getUser(user.getId()); } }
三
-
SqlSessionFactoryBean來替代SqlSessionFactoryBuilder創建SqlSession
-
不采用采用數據映射器(MapperFactoryBean)的方式,改為MapperScannerConfigurer 進行掃描
-
不用寫mybatis映射文件
-
采用註解方式提供相應的sql語句和輸入參數。
-
采用註解方式省去定義mapper的Bean
MapperFactoryBean 創建的代理類實現了 UserMapper 接口,並且註入到應用程序中。 因為代理創建在運行時環境中(Runtime,譯者註) ,那麽指定的映射器必須是一個接口,而 不是一個具體的實現類。
上面的MapperFactoryBean配置有一個很大的缺點,就是系統有很多的配置文件時 全部需要手動編寫,所以上述的方式已經不用了。
沒有必要在 Spring 的 XML 配置文件中註冊所有的映射器。相反,你可以使用一個 MapperScannerConfigurer , 它將會查找類路徑下的映射器並自動將它們創建成MapperFactoryBean。
Spring的xml配置:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="org.mybatis.spring.sample.mapper" /> </bean>
basePackage 屬性是讓你為映射器接口文件設置基本的包路徑。 你可以使用分號或逗號 作為分隔符設置多於一個的包路徑。每個映射器將會在指定的包路徑中遞歸地被搜索到。
註 意 , 沒有必要去指定SqlSessionFactory 或 SqlSessionTemplate , 因為 MapperScannerConfigurer 將會創建MapperFactoryBean,之後自動裝配。但是,如果你使 用了一個 以上的 DataSource,那 麽自動裝配可能會失效 。這種情況下 ,你可以使用 sqlSessionFactoryBeanName 或 sqlSessionTemplateBeanName 屬性來設置正確的 bean 名稱來使用。
Spring-Mybatis --- 配置SqlSessionFactoryBean,整合Spring-Mybatis(轉)