1. 程式人生 > >Spring之Mybatis整合

Spring之Mybatis整合

一、資料來源交給Spring

1.db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

2.spring管理資料來源

   <!-- 載入資料庫配置檔案 -->
   <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 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>
</beans>

二、sqlSessionFactory會話工程物件配置到Spring容器(別名交給Spring)

    <!--會話工廠bean sqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 資料來源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 核心配置檔案 -->
        <property name="configLocation" value="classpath:SqlMapConfig.xml"/>
        <!-- 別名 -->
        <property name="typeAliasesPackage" value="com.mark.pojo"/>
    </bean>

三、mappers(對映配置)交給Spring

1.傳統Dao層開發

(1)在SqlMapConfig.xml主配置檔案中引入mappers對映檔案

<configuration>
    <!--加入實體資料庫對映檔案-->
    <mappers>
	<!-- 註冊userMapper.xml檔案
    userMapper.xml位於com.mark.mapping這個包下,所以resource寫成com/mark/mapping/userMapper.xml-->
	<mapper resource="com/mark/mapping/userMapper.xml"/>
    </mappers>
 
</configuration>

(2)在applicationContext.xml中配置UserDaoImpl實現類,注入sqlSessionFactory

    <!-- 傳統dao  -->
	<bean class="com.mark.mybatis.dao.impl.UserDaoImpl">
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>

(3)UserDao介面實現類

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {

	@Override
	public User getUserById(Integer id) {
		SqlSession sqlSession = super.getSqlSession();
		//查詢使用者
		User user = sqlSession.selectOne("user.getUserById", id);
		
		//不能關閉sqlSession,sqlSession由Spring管理
		//sqlSession.close();
		return user;
	}
}

2.Mapper代理模式開發Dao(不需要自己寫實現類)

(1)單個介面配置MapperFactoryBean

    <!-- 動態代理Dao開發,第一種方式 -MapperFactoryBean -->
    <bean id="baseMapper" class="org.mybatis.spring.mapper.MapperFactoryBean" abstract="true" lazy-init="true">
     	<property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
    <!-- 使用者動態代理掃描 -->
    <bean parent="baseMapper">
      <property name="mapperInterface" value="com.mark.mybatis.mapper.UserMapper" />
    </bean>

(2) 配置包掃描器(推薦)

    <!-- 動態代理Dao開發,第一種方式,包掃描器(推薦使用) -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定會話工廠,如果當前上下文中只定義了一個則該屬性可省去 -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- basePackage:配置對映包裝掃描,多個包時用","或";"分隔 -->
        <property name="basePackage" value="com.mark.mybatis.mapper" />
   </bean>