1. 程式人生 > >MyBatis(9)整合spring

MyBatis(9)整合spring

具體的感興趣可以參考:MyBatis

此時此刻,沒用的話不再多說了,直接開始程式碼工程吧!

整體的程式碼實現:

具體使用到的我們在進行細說

基本上理解一邊就能會使用整合

 準備工作:

 db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3307/shopping
jdbc.username=root
jdbc.password=12345

 log4j.properties

#Global logging configuration
# 在開發環境下日誌級別要設成
log4j.rootLogger 
= DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern =%5p [%t] - %m%n
applivationContext.xml mvc,context,aop,tx,beans...命名約束
     <!-- 載入配置檔案 -->
     <context:property-placeholder location="classpath:db.properties" />

 使用dbcp資料庫連線池

<!-- 資料來源,使用dbcp -->
     <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>
配置SqlSessionFactory

 不需要在類中單獨進行配置

<!-- sqlSessinFactory -->
     <!-- org.mybatis.spring.SqlSessionFactoryBean -->
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
           <!-- 載入mybatis的配置檔案 -->
           <property name="configLocation" value="mybatis/SqlMapConfig.xml" />
           <!-- 資料來源 -->
           <property name="dataSource" ref="dataSource" />
     </bean>

 SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
     <typeAliases>
           <package name="com.MrChengs.po"/>
     </typeAliases>  
     
     <!-- 載入 對映檔案 -->
     <mappers>
           <mapper resource="sqlmap/User.xml"/>
     </mappers>
</configuration>

 其他的設定項在使用的時候在進行新增,,,,,,

 一.dao開發

 Userser.xml

 簡單的小案例進行測試,其餘的程式碼和之前的方法一樣

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
     <select id="findUserByID" parameterType="int" resultType="com.MrChengs.po.User">
           select * from user where id=#{id}
     </select>
</mapper>

 UserDao.java

public interface UserDao {
     //根據id查詢使用者資訊
     public User findUserById(int id) throws Exception;
}

 UserDaoImp.java

讓實現介面類的類繼承SqlSessionDaoSupport 通過spring進行注入,宣告配置方式,配置dao的bean 此時不需要手動配置SqlSessionFactory 直接可以得到其物件 此時不需要手動關閉,在spring容器池裡會自動關閉
public class UserDaoImp extends SqlSessionDaoSupport implements UserDao {
     @Override
     public User findUserById(int id) throws Exception {
           SqlSession sqlSession = this.getSqlSession();
           User user =sqlSession.selectOne("test.findUserByID", id);
           return user;
     }
}
applivationContext.xml 注入sqlSessionFactory
     <bean id="userDao" class="com.MrChengs.UserDao.UserDaoImp">
           <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
     </bean>

測試:

public class Test {
     private ApplicationContext applicationContext;
     public ApplicationContext getApplication(){
           applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
           return applicationContext;
     }
     //Dao開發
     @org.junit.Test
     public void testDao() throws Exception{
           UserDao userdao = (UserDao) getApplication().getBean("userDao");
           User user =  userdao.findUserById(1);
           System.out.println(user);
     }
}
DEBUG [main] - ==>  Preparing: select * from user where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - Closing non transactional SqlSession [[email protected]]
DEBUG [main] - Returning JDBC Connection to DataSource
User [id=1, username=王五, birthday=null, sex=2, address=null]

二.Mapper代理開發

UserMapper.java

//相當於dao介面
public interface UserMapper {
     //根據id查詢使用者資訊
     public User findUserById(int id) throws Exception;
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.MrChengs.mapper.UserMapper">
     <select id="findUserById" parameterType="int" resultType="com.MrChengs.po.User">
           SELECT * FROM USER WHERE id=#{value}
     </select>
</mapper>

注意上述的兩個檔案在一個路徑下。

SqlMapConfig.xml

     <!-- 載入 對映檔案 -->
     <mappers>
           <mapper resource="sqlmap/User.xml"/>
           <package name="com.MrChengs.mapper"/>
     </mappers>

通過MapperFactoryBean建立代理物件

<!-- mapper配置
     MapperFactoryBean:根據mapper介面生成代理物件
-->
     <!-- mapperInterface指定mapper介面 -->
     <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
           <property name="mapperInterface" value="com.MrChengs.mapper.UserMapper"/>
           <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
     </bean>

測試:

public class TestMapper {
     private ApplicationContext applicationContext;
     public ApplicationContext getApplication(){
           applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
           return applicationContext;
     }
     //Mapper開發
     @org.junit.Test
     public void testmapper() throws Exception{
           UserMapper user = (UserMapper) getApplication().getBean("userMapper");
           User u = user.findUserById(1);
           System.out.println(u);
     }
}
DEBUG [main] - ==>  Preparing: SELECT * FROM USER WHERE id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - Closing non transactional SqlSession [[email protected]]
DEBUG [main] - Returning JDBC Connection to DataSource
User [id=1, username=王五, birthday=null, sex=2, address=null]

如果有很多個類都需要對每個mapper進行配置,此時需要大量的工程???

     <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
           <property name="mapperInterface" value="com.MrChengs.mapper.UserMapper"/>
           <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
     </bean>
。。。。。

通過MapperScannerConfigurer進行mapper掃描(建議使用)

applicationContext.xml

說明:

mapper批量掃描,從mapper包中掃描出mapper介面,自動建立代理物件並且在spring容器中註冊 遵循規範:將mapper.java和mapper.xml對映檔名稱保持一致,且在一個目錄 中 自動掃描出來的mapper的bean的id為mapper類名(首字母小寫
name="basePackage"
指定掃描的包名
如果掃描多個包,每個包中間使用半形逗號分隔
     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     <property name="basePackage" value="com.MrChengs.mapper"/>
     <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
     
     </bean>

 其餘的測試不變......