1. 程式人生 > 程式設計 >MyBatis與Spring整合過程例項解析

MyBatis與Spring整合過程例項解析

這篇文章主要介紹了MyBatis與Spring整合過程例項解析,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

從之前的程式碼中可以看出直接使用 MyBatis 框架的 SqlSession 訪問資料庫並不簡便。MyBatis 框架的重點是 SQL 對映檔案,為方便後續學習,本節講解 MyBatis 與 Spring 的整合。教程的後續講解中將使用整合後的框架進行演示。

匯入相關JAR包

1)MyBatis 框架所需的 JAR 包

                                       MyBatis與Spring整合過程例項解析
                                           

圖 1MyBatis相關的JAR包

2)Spring 框架所需的 JAR 包

  • aopalliance-1.0.jar
  • aspectjweaver-1.6.9.jar
  • spring-aop-3.2.13.RELEASE.jar
  • spring-aspects-3.2.13.RELEASE.jar
  • spring-beans-3.2.13.RELEASE.jar
  • spring-context-3.2.13.RELEASE.jar
  • spring-core-3.2.13.RELEASE.jar
  • spring-expression-3.2.13.RELEASE.jar
  • spring-jdbc-3.2.13.RELEASE.jar
  • spring-tx-3.2.13.RELEASE.jar

3)MyBatis 與 Spring 整合的中間 JAR 包

該中間 JAR 包的版本為 mybatis-spring-1.3.1.jar,此版本可以從網址“http://mvnrepository.com/artifact/org.mybatis/mybatis-spring/1.3.1”下載。

4)資料庫驅動 JAR 包

教程所使用的Mybatis資料庫驅動包為 mysql-connector-java-5.1.25-bin.jar。

5)資料來源所需的 JAR 包

在整合時使用的是 DBCP 資料來源,需要準備 DBCP 和連線池的 JAR 包。

本教程所用版本的 DBCP 的 JAR 包為 commons-dbcp2-2.2.0.jar,可以從網址“htttp://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi”下載。

最新版本的連線池的 JAR 包為 commons-pool2-2.5.0.jar,可以從網址“http://commons.apache.org/proper/commons-pool/download_pool.cgi”下載。

在Spring中配置MyBatis工廠

通過與 Spring 的整合,MyBatis 的 SessionFactory 交由 Spring 來構建,在構建時需要在 Spring 的配置檔案中新增如下程式碼:

<!--配置資料來源-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/springtest?seUnicode=true&characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="1128" />
<!-- 最大連線數 -->
<property name="maxTotal" value="30"/>
<!-- 最大空閒連線數 -->
<property name="maxIdle" value="10"/>
<!-- 初始化連線數 -->
<property name="initialSize" value="5"/>
</bean>
<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 引用資料來源元件 -->
<property name="dataSource" ref="dataSource" />
<!-- 引用MyBatis配置檔案中的配置 -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>

使用 Spring 管理 MyBatis 的資料操作介面

使用 Spring 管理 MyBatis 資料操作介面的方式有多種,其中最常用、最簡潔的一種是基於 MapperScannerConfigurer 的整合。該方式需要在 Spring 的配置檔案中加入以下內容:

<!-- Mapper代理開發,使用Spring自動掃描MyBatis的介面並裝配 (Sprinh將指定包中的所有被@Mapper註解標註的介面自動裝配為MyBatis的對映介面) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- mybatis-spring元件的掃描器,com.dao只需要介面(介面方法與SQL對映檔案中的相同) -->
<property name="basePackage" value="com.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

專案結構

MyBatis與Spring整合過程例項解析

第一步:entity層

public class City implements Serializable {

 private long cid;
 private String cname;
 private long pid;


 public long getCid() {
  return cid;
 }

 public void setCid(long cid) {
  this.cid = cid;
 }


 public String getCname() {
  return cname;
 }

 public void setCname(String cname) {
  this.cname = cname;
 }


 public long getPid() {
  return pid;
 }

 public void setPid(long pid) {
  this.pid = pid;
 }

}

第二步:Dao層

@MapperScan
public interface UserMapper {
  public City getUserList(Integer cid);
}

第三步:service層

public interface UserService {
  public City getUserList(Integer cid);
}

第四步:service實現層

@Service("userService")
public class UserServiceImpl implements UserService {
  @Resource
  private UserMapper userMapper;//宣告UserMapper介面引用


  @Override
  public City getUserList(Integer cid) {

    return userMapper.getUserList(cid);
  }
}

第五步:CityMapper.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTO Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.smbms.dao.UserMapper">
  <!--查-->
  <select id="getUserList" resultType="cn.smbms.entity.City"><!--resultMap屬性值指向resultMap節點的ID-->
    select * from city where cid=#{cid}
  </select>

</mapper>

第六步:applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--根節點是我們的beans節點-->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

  <!-- 自動掃描 -->
  <context:component-scan base-package="cn.smbms" />
  <!-- 引入配置檔案 -->
  <context:property-placeholder location="classpath:jdbc.properties"/>
  <!-- 資料來源配置-->
  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
  </bean>
  <!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案 -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <!--別名-->
    <property name="typeAliasesPackage" value="cn.smbms.entity"/>
    <!-- 自動掃描mapping.xml檔案,**表示迭代查詢 -->
    <property name="mapperLocations" value="classpath*:mapper/*.xml" />
  </bean>

  <!-- DAO介面所在包名,Spring會自動查詢其下的類,包下的類需要使用@MapperScan註解,否則容器注入會失敗 -->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.smbms.dao" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
  </bean>

  <!-- (事務管理)transaction manager,use JtaTransactionManager for global tx -->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
  </bean>
</beans>

第七步:jdbc.properties

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

第八步:mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- xml檔案的標頭檔案,起到對檔案的約束作用(例如:必須存在哪些節點) -->
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--核心配置-->
</configuration>

第九步:測試

@Test
  public void shouldAnswerWithTrue()
  {
    ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService)ctx.getBean("userService");
    City userList = userService.getUserList(130000);
    System.out.println(userList.getCname());

  }

以上程式碼是基於註解,如果想要XML方式,下面就是,謝謝根據上面的進行修改:修改applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--根節點是我們的beans節點-->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

  <!-- 自動掃描 -->
  <context:component-scan base-package="cn.smbms" />
  <!-- 引入配置檔案 -->
  <context:property-placeholder location="classpath:jdbc.properties"/>
  <!-- 資料來源配置-->
  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
  </bean>
  <!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案 -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <!--別名-->
    <property name="typeAliasesPackage" value="cn.smbms.entity"/>
    <!-- 自動掃描mapping.xml檔案,**表示迭代查詢 -->
    <property name="mapperLocations" value="classpath*:mapper/*.xml" />
  </bean>

  <!-- DAO介面所在包名,Spring會自動查詢其下的類,否則容器注入會失敗 -->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.smbms.dao" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
  </bean>

  <bean id="userService" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="cn.smbms.dao.UserMapper"/>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
  </bean>
 <!-- Service層-->
  <bean id="iBankService" class="cn.smbms.service.impl.UserServiceImpl">
    <property name="UserMapper" ref="userService"/>
  </bean>-->

  <!-- (事務管理)transaction manager,use JtaTransactionManager for global tx -->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
  </bean>
</beans>

修改Dao層

public interface UserMapper {
  public City getUserList(Integer cid);
}

修改Service實現類

public class UserServiceImpl implements UserService {


  public UserMapper getUserMapper() {
    return userMapper;
  }

  public void setUserMapper(UserMapper userMapper) {
    this.userMapper = userMapper;
  }

  private UserMapper userMapper;//宣告UserMapper介面引用


  @Override
  public City getUserList(Integer cid) {

    return userMapper.getUserList(cid);
  }
}

以上都是對Spring和Mybatis進行整合,希望對你有一些幫助,謝謝

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。