• spring与mybatis四种整合方法


    一、采用org.mybatis.spring.mapper.MapperScannerConfigurer

    整体结构如下图:

    1、配置文件

    1>applicationContext01.xml

     

    1. <?xmlversionxmlversion="1.0"encoding="UTF-8"?>  
    2. <beansxmlns:xsibeansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"  
    3.   xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"  
    4.   xmlns:tx="http://www.springframework.org/schema/tx"xmlns:cache="http://www.springframework.org/schema/cache"  
    5.   xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans  
    6.      http://www.springframework.org/schema/beans/spring-beans.xsd  
    7.     http://www.springframework.org/schema/aop  
    8.     http://www.springframework.org/schema/aop/spring-aop.xsd  
    9.     http://www.springframework.org/schema/context  
    10.     http://www.springframework.org/schema/context/spring-context.xsd  
    11.     http://www.springframework.org/schema/tx  
    12.     http://www.springframework.org/schema/tx/spring-tx.xsd  
    13.      http://www.springframework.org/schema/cache  
    14.     http://www.springframework.org/schema/cache/spring-cache.xsd">  
    15.       
    16.     <!-- 自动扫描 -->  
    17.     <context:component-scanbase-packagecontext:component-scanbase-package="com.hys.app.**.service,com.hys.app.**.dao,com.hys.app.**.action"/>  
    18.     <!-- 引入外置文件 -->  
    19.     <beanidbeanid="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    20.         <propertynamepropertyname="location"value="classpath:jdbc.properties"/>  
    21.     </bean>  
    22.      
    23.     <!--数据库连接池配置-->  
    24.     <beanidbeanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">    
    25.         <propertynamepropertyname="driverClassName"value="${jdbc.driverClassName}"/>  
    26.         <propertynamepropertyname="url"value="${jdbc.url}"/>  
    27.         <propertynamepropertyname="username"value="${jdbc.username}"/>  
    28.         <propertynamepropertyname="password"value="${jdbc.password}"/>  
    29.     </bean>  
    30.    
    31.     <!-- spring和MyBatis完美整合 -->  
    32.     <beanidbeanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">  
    33.         <!-- 指定数据源 -->  
    34.         <propertynamepropertyname="dataSource"ref="dataSource"/>  
    35.         <!-- 具体指定xml文件,可不配 -->  
    36.         <propertynamepropertyname="configLocation" value="classpath:mybatis-config.xml"/>  
    37.         <!-- 自动扫描mapping.xml文件,**表示迭代查找 ,,也可在mybatis-config.xml中单独指定xml文件 -->  
    38.         <propertynamepropertyname="mapperLocations"value="classpath:com/hys/app/**/dao/*.xml"/>  
    39.     </bean>  
    40.    
    41.     <!-- 自动扫描com/hys/app/**/dao下的所有dao接口,并实现这些接口,可直接在程序中使用dao接口,不用再获取sqlsession对象 -->  
    42.     <beanclassbeanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">  
    43.         <!--  
    44.         basePackage 属性是映射器接口文件的包路径。  
    45.                  你可以使用分号或逗号 作为分隔符设置多于一个的包路径  
    46.         -->  
    47.         <propertynamepropertyname="basePackage"value="com/hys/app/**/dao"/>  
    48.         <!--  
    49.                  因为会自动装配 SqlSessionFactory和SqlSessionTemplate  
    50.                  所以没 有 必 要 去 指 定 SqlSessionFactory或 SqlSessionTemplate  
    51.                  因此可省略不配置;  
    52.                  但是,如果你使 用了一个 以上的 DataSource,那么自动装配可能会失效。  
    53.                  这种 情况下,你可以使用sqlSessionFactoryBeanName或sqlSessionTemplateBeanName属性来设置正确的 bean名称来使用;  
    54.         -->  
    55.         <propertynamepropertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"/>  
    56.     </bean>  
    57.      
    58.     <!-- 事务管理器  
    59.     <bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
    60.         <propertynamepropertyname="dataSource" ref="dataSource" />  
    61.     </bean>    
    62.     -->  
    63.     <!-- 使用声明式事务   
    64.     <tx:annotation-driventransaction-managertx:annotation-driventransaction-manager="txManager" />  
    65.     -->  
    66. </beans>  

    2>jdbc.properties外置文件

     

    1. jdbc.driverClassName=com.mysql.jdbc.Driver  
    2. jdbc.url=jdbc:mysql://localhost:3306/demo?characterEncoding=UTF-8  
    3. jdbc.username=root  
    4. jdbc.password=root  

    3>mybatis-config.xml

     

    1. <?xmlversionxmlversion="1.0"encoding="UTF-8"?>  
    2. <!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTDConfig 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">    
    3.    
    4. <configuration>  
    5.     <typeAliases>  
    6.        <typeAliastypetypeAliastype="com.hys.app.student.entity.Student"alias="Student"/>  
    7.     </typeAliases>  
    8. </configuration>  

    4>studentMapper.xml

     

    1. <?xmlversionxmlversion="1.0"encoding="UTF-8"?>  
    2. <!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
    3.    
    4. <mappernamespacemappernamespace="com.hys.app.student.dao.StudentDao">  
    5.      
    6.     <insertidinsertid="save"parameterType="Student">  
    7.         insert intot_app_student(id,name,sex,age) values(#{id},#{name},#{sex},#{age})  
    8.     </insert>    
    9.     <selectidselectid="getStudent"resultType="Student"parameterType="String">  
    10.         select * from t_app_student where id =#{id}  
    11.     </select>    
    12. </mapper>  

    5>pom.xml

     

    1. <projectxmlnsprojectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">  
    3.   <modelVersion>4.0.0</modelVersion>  
    4.    
    5.   <groupId>hys.web.project</groupId>  
    6.   <artifactId>hys_demo_ssm</artifactId>  
    7.   <version>0.0.1-SNAPSHOT</version>  
    8.   <packaging>jar</packaging>  
    9.   <name>hys_demo_ssm</name>  
    10.   <url>http://maven.apache.org</url>  
    11.    
    12.   <properties>  
    13.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
    14.   </properties>  
    15.    
    16.   <dependencies>  
    17.     <dependency>  
    18.       <groupId>junit</groupId>  
    19.       <artifactId>junit</artifactId>  
    20.       <version>4.10</version>  
    21.       <scope>test</scope>  
    22.     </dependency>  
    23.      
    24.     <!-- 数据源 -->  
    25.     <dependency>  
    26.         <groupId>commons-dbcp</groupId>  
    27.         <artifactId>commons-dbcp</artifactId>  
    28.         <version>1.4</version>  
    29.     </dependency>  
    30.      
    31.        <dependency>  
    32.        <groupId>mysql</groupId>  
    33.        <artifactId>mysql-connector-java</artifactId>  
    34.        <version>5.0.8</version>  
    35.     </dependency>  
    36.      
    37.     <!-- Mybatis3.4.1 -->  
    38.     <dependency>  
    39.         <groupId>org.mybatis</groupId>  
    40.         <artifactId>mybatis</artifactId>  
    41.         <version>3.4.1</version>  
    42.     </dependency>  
    43.      
    44.     <!-- spring整合mybatis -->  
    45.     <dependency>  
    46.         <groupId>org.mybatis</groupId>  
    47.         <artifactId>mybatis-spring</artifactId>  
    48.         <version>1.3.0</version>  
    49.     </dependency>  
    50.      
    51.     <!-- Spring-4.2.0 -->  
    52.     <dependency>  
    53.         <groupId>org.springframework</groupId>  
    54.         <artifactId>spring-web</artifactId>  
    55.         <version>4.2.0.RELEASE</version>  
    56.     </dependency>  
    57.      
    58.     <dependency>  
    59.         <groupId>org.springframework</groupId>  
    60.         <artifactId>spring-orm</artifactId>  
    61.         <version>4.2.0.RELEASE</version>  
    62.     </dependency>  
    63.      
    64.     <dependency>  
    65.         <groupId>org.springframework</groupId>  
    66.         <artifactId>spring-expression</artifactId>  
    67.         <version>4.2.0.RELEASE</version>  
    68.     </dependency>  
    69.      
    70.   </dependencies>  
    71. </project>  

    建立表: 

    1. CREATE TABLE t_app_student  
    2. ( id VARCHAR(32) NOT NULL PRIMARY KEY,  
    3.   name VARCHAR(15),  
    4.   sex VARCHAR(2),  
    5.   age INT  
    6. )  

    2、创建action、service、dao、entity类

    1>实体类Student

     

    1. packagecom.hys.app.student.entity;  
    2.    
    3. public class Student {  
    4.      
    5.     private Stringid;  
    6.     private Stringname;  
    7.     private Stringsex;  
    8.     private int age;  
    9.      
    10.     publicStudent(){  
    11.         
    12.     }    
    13.     publicStudent(Stringid, Stringname, Stringsex,intage) {  
    14.        this.id =id;  
    15.        this.name =name;  
    16.        this.sex =sex;  
    17.        this.age =age;  
    18.     }  
    19.     public StringgetId() {  
    20.        returnid;  
    21.     }  
    22.     public void setId(String id) {  
    23.        this.id =id;  
    24.     }  
    25.     public StringgetName() {  
    26.        returnname;  
    27.     }  
    28.     public void setName(String name) {  
    29.        this.name =name;  
    30.     }  
    31.     public StringgetSex() {  
    32.        returnsex;  
    33.     }  
    34.     public void setSex(String sex) {  
    35.        this.sex =sex;  
    36.     }  
    37.     public int getAge() {  
    38.        returnage;  
    39.     }  
    40.     public void setAge(intage) {  
    41.        this.age =age;  
    42.     }  
    43.     @Override  
    44.     public StringtoString() {  
    45.        return"Student [id=" +id +", name=" +name +", sex=" +sex  
    46.               + ", age=" + age + "]";  
    47.     }  
    48.      
    49. }  

    2>dao接口

     

    1. packagecom.hys.app.student.dao;  
    2. importcom.hys.app.student.entity.Student;  
    3.    
    4. public interface StudentDao {  
    5.    public void save(Student student);  
    6.    public Student getStudent(Stringid);  
    7. }  

    3>service服务

    1. packagecom.hys.app.student.service;  
    2. importorg.springframework.beans.factory.annotation.Autowired;  
    3. importorg.springframework.stereotype.Service;  
    4. importcom.hys.app.student.dao.StudentDao;  
    5. importcom.hys.app.student.entity.Student;  
    6.    
    7. @Service  
    8. publicclass StudentService {  
    9.      
    10.     @Autowired  
    11.     private StudentDao studentDao;  
    12.      
    13.     public void save(Student student) {  
    14.        studentDao.save(student);  
    15.     }  
    16.      
    17.     public Student getStudent(String id) {  
    18.        Student student =studentDao.getStudent(id);  
    19.        return student;  
    20.     }  
    21.      
    22. }  

    4>action测试类

    1. packagecom.hys.app.student.action;  
    2. importorg.junit.Test;  
    3. importorg.springframework.beans.factory.annotation.Autowired;  
    4. importorg.springframework.context.ApplicationContext;  
    5. importorg.springframework.context.support.ClassPathXmlApplicationContext;  
    6. importorg.springframework.stereotype.Controller;  
    7. importcom.hys.app.student.entity.Student;  
    8. importcom.hys.app.student.service.StudentService;  
    9.    
    10. @Controller  
    11. publicclass StudentAction {  
    12.      
    13.     @Autowired  
    14.     private StudentService studentService;  
    15.    
    16.     @Test  
    17.     public void test1(){  
    18.        //获取上下文对象  
    19.        ApplicationContext context =newClassPathXmlApplicationContext("applicationContext01.xml");  
    20.        StudentAction studentAction =(StudentAction)context.getBean("studentAction");  
    21.         
    22. //     Student student = newStudent("002","小明","男",20);  
    23. //     studentAction.studentService.save(student);  
    24.        Student std = studentAction.studentService.getStudent("001");  
    25.        System.out.println(std);  
    26.     }  
    27. }  

    注:重复的文件在下面的例子中不在贴出来,在测试类中注意替换applicationContext01.xml文件名

    二、采用数据映射器(MapperFactoryBean)的方式,不用写mybatis映射文件,采用注解方式提供相应的sql语句和输入参数

    整体结构如下图:

    1、配置文件

    applicationContext04.xml

     

    1. <?xmlversionxmlversion="1.0"encoding="UTF-8"?>  
    2. <beansxmlns:xsibeansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"  
    3.   xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"  
    4.   xmlns:tx="http://www.springframework.org/schema/tx"xmlns:cache="http://www.springframework.org/schema/cache"  
    5.   xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans  
    6.      http://www.springframework.org/schema/beans/spring-beans.xsd  
    7.      http://www.springframework.org/schema/aop  
    8.     http://www.springframework.org/schema/aop/spring-aop.xsd  
    9.     http://www.springframework.org/schema/context  
    10.      http://www.springframework.org/schema/context/spring-context.xsd  
    11.      http://www.springframework.org/schema/tx  
    12.     http://www.springframework.org/schema/tx/spring-tx.xsd  
    13.     http://www.springframework.org/schema/cache  
    14.     http://www.springframework.org/schema/cache/spring-cache.xsd">  
    15.       
    16.     <!-- 自动扫描 -->  
    17.     <context:component-scanbase-packagecontext:component-scanbase-package="com.hys.app.**.service,com.hys.app.**.dao,com.hys.app.**.action"/>  
    18.     <!-- 引入外置文件 -->  
    19.     <beanidbeanid="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    20.        <propertynamepropertyname="location"value="classpath:jdbc.properties"/>  
    21.     </bean>  
    22.      
    23.     <!--数据库连接池配置-->  
    24.     <beanidbeanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">    
    25.        <propertynamepropertyname="driverClassName"value="${jdbc.driverClassName}"/>  
    26.        <propertynamepropertyname="url"value="${jdbc.url}"/>  
    27.        <propertynamepropertyname="username"value="${jdbc.username}"/>  
    28.         <propertynamepropertyname="password"value="${jdbc.password}"/>  
    29.     </bean>  
    30.    
    31.     <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  
    32.     <beanidbeanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">  
    33.        <propertynamepropertyname="dataSource"ref="dataSource"/>  
    34.     </bean>  
    35.    
    36.     <!--  
    37.     创建数据映射器,数据映射器必须为接口  
    38.     这种配置方式有个缺点,有多少个dao接口就要配置多少个数据映射器,增加了开发时间  
    39.     可用MapperScannerConfigurer代替,能够完全解决问题  
    40.    <bean id="studentMapper"class="org.mybatis.spring.mapper.MapperFactoryBean">    
    41.         <propertynamepropertyname="mapperInterface"value="com.hys.app.student.dao.StudentDao" />   
    42.         <propertynamepropertyname="sqlSessionFactory"ref="sqlSessionFactory"/>  
    43.    </bean>   
    44.    -->   
    45.      
    46.     <!-- 自动扫描com/hys/app/**/dao下的所有dao接口,并实现这些接口,可直接在程序中使用dao接口,不用再获取sqlsession对象 -->  
    47.     <beanclassbeanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">  
    48.        <!--  
    49.        basePackage 属性是映射器接口文件的包路径。  
    50.                  你可以使用分号或逗号作为分隔符设置多于一个的包路径  
    51.        -->  
    52.        <propertynamepropertyname="basePackage"value="com/hys/app/**/dao"/>  
    53.        <!--  
    54.                  因为会自动装配 SqlSessionFactory和SqlSessionTemplate  
    55.                  所以没 有 必 要去 指 定 SqlSessionFactory或SqlSessionTemplate  
    56.                  因此可省略不配置;  
    57.                  但是,如果你使 用了一个 以上的 DataSource,那么自动装配可能会失效。  
    58.                  这种 情况下,你可以使用sqlSessionFactoryBeanName或sqlSessionTemplateBeanName属性来设置正确的 bean名称来使用;  
    59.        -->  
    60.        <propertynamepropertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"/>  
    61.     </bean>  
    62.      
    63.     <!-- 事务管理器  
    64.    <bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
    65.        <property name="dataSource" ref="dataSource"/>  
    66.    </bean>    
    67.    -->  
    68.     <!-- 使用声明式事务   
    69.    <tx:annotation-driven transaction-manager="txManager" />  
    70.    -->  
    71. </beans>  

    2、创建action、service、dao、entity类

    1>dao接口

    1. packagecom.hys.app.student.dao;  
    2. importorg.apache.ibatis.annotations.Insert;  
    3. importorg.apache.ibatis.annotations.Select;  
    4. importcom.hys.app.student.entity.Student;  
    5.    
    6. publicinterface StudentDao {  
    7.     @Insert(" insert intot_app_student(id,name,sex,age) values(#{id},#{name},#{sex},#{age})")  
    8.     public void save(Student student);  
    9.     @Select("select * from t_app_studentwhere id = #{id}")  
    10.     public Student getStudent(String id);  
    11. }  

    2>service服务

    1. packagecom.hys.app.student.service;  
    2. importorg.springframework.beans.factory.annotation.Autowired;  
    3. importorg.springframework.stereotype.Service;  
    4. importcom.hys.app.student.dao.StudentDao;  
    5. importcom.hys.app.student.entity.Student;  
    6.    
    7. @Service  
    8. publicclass StudentService {  
    9.      
    10.     @Autowired  
    11.     private StudentDao studentDao;  
    12.      
    13.     public void save(Student student) {  
    14.        studentDao.save(student);  
    15.     }  
    16.      
    17.     public Student getStudent(String id) {  
    18.        Student student =studentDao.getStudent(id);  
    19.        return student;  
    20.     }  
    21.      
    22. }  

     三、采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供SqlSession

    整体结构如下图:

    1、配置文件

    applicationContext03.xml

    1. <?xmlversionxmlversion="1.0"encoding="UTF-8"?>  
    2. <beansxmlns:xsibeansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"  
    3.   xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"  
    4.   xmlns:tx="http://www.springframework.org/schema/tx"xmlns:cache="http://www.springframework.org/schema/cache"  
    5.   xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans  
    6.      http://www.springframework.org/schema/beans/spring-beans.xsd  
    7.      http://www.springframework.org/schema/aop  
    8.     http://www.springframework.org/schema/aop/spring-aop.xsd  
    9.     http://www.springframework.org/schema/context  
    10.     http://www.springframework.org/schema/context/spring-context.xsd  
    11.     http://www.springframework.org/schema/tx  
    12.      http://www.springframework.org/schema/tx/spring-tx.xsd  
    13.     http://www.springframework.org/schema/cache  
    14.     http://www.springframework.org/schema/cache/spring-cache.xsd">  
    15.       
    16.     <!-- 自动扫描 -->  
    17.     <context:component-scanbase-packagecontext:component-scanbase-package="com.hys.app.**.service,com.hys.app.**.dao,com.hys.app.**.action"/>  
    18.     <!-- 引入外置文件 -->  
    19.     <beanidbeanid="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    20.         <propertynamepropertyname="location"value="classpath:jdbc.properties"/>  
    21.     </bean>  
    22.      
    23.     <!--数据库连接池配置-->  
    24.     <beanidbeanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">    
    25.        <propertynamepropertyname="driverClassName"value="${jdbc.driverClassName}"/>  
    26.        <propertynamepropertyname="url"value="${jdbc.url}"/>  
    27.        <propertynamepropertyname="username"value="${jdbc.username}"/>  
    28.         <propertynamepropertyname="password"value="${jdbc.password}"/>  
    29.     </bean>  
    30.    
    31.     <beannamebeanname="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">  
    32.       <propertynamepropertyname="dataSource"ref="dataSource"/>  
    33.       <propertynamepropertyname="mapperLocations"value="classpath:com/hys/app/**/dao/*.xml"/>  
    34.     </bean>  
    35.      
    36.     <!-- 将sqlSessionTemplate手工注入到SqlSessionDaoSupport中 -->  
    37.     <beanidbeanid="sqlSessionTemplate"class="org.mybatis.spring.SqlSessionTemplate">  
    38.         <constructor-argindexconstructor-argindex="0"ref="sqlSessionFactory"/>  
    39.     </bean>  
    40.      
    41. </beans>  

    studentMapper.xml

     

    1. <?xmlversionxmlversion="1.0"encoding="UTF-8"?>  
    2. <!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
    3.    
    4. <mappernamespacemappernamespace="com.hys.app.student.dao.StudentDao">  
    5.     <insertidinsertid="save"parameterType="com.hys.app.student.entity.Student">  
    6.         insert intot_app_student(id,name,sex,age) values(#{id},#{name},#{sex},#{age})  
    7.     </insert>   
    8.     <selectidselectid="getStudent"resultType="com.hys.app.student.entity.Student"parameterType="String">  
    9.         select * from t_app_student where id =#{id}  
    10.     </select>     
    11. </mapper>  

    2、创建action、service、dao、entity类

    1>dao接口

     

    1. packagecom.hys.app.student.dao;  
    2. importcom.hys.app.student.entity.Student;  
    3.    
    4. public interface StudentDao {  
    5.     public void save(Student student);  
    6.     public StudentgetStudent(Stringid);  
    7. }  

    2>dao接口实现类

    1. packagecom.hys.app.student.dao;  
    2. importjavax.annotation.Resource;  
    3. importorg.mybatis.spring.SqlSessionTemplate;  
    4. importorg.mybatis.spring.support.SqlSessionDaoSupport;  
    5. importorg.springframework.stereotype.Service;  
    6. importcom.hys.app.student.entity.Student;  
    7.    
    8. @Service  
    9. publicclass StudentDaoImp extends SqlSessionDaoSupport implements StudentDao{  
    10.      
    11.      /**  
    12.       * 我们发现这个类中没有把SqlSessionTemplate作为一个属性,因为我们继承了SqlSessionDaoSupport  
    13.       *SqlSessionDaoSupport他会提供sqlsession  
    14.      */  
    15.    
    16.     @Override  
    17.     public void save(Student student) {  
    18.        // TODO Auto-generated method stub  
    19.        this.getSqlSession().insert("com.hys.app.student.dao.StudentDao.save",student);  
    20.     }  
    21.    
    22.     @Override  
    23.     public Student getStudent(String id) {     
    24.        // TODO Auto-generated method stub  
    25.        returnthis.getSqlSession().selectOne("com.hys.app.student.dao.StudentDao.getStudent",id);  
    26.     }  
    27.    
    28.     /**  
    29.      * 使用SqlSessionDaoSupport必须注意,此处源码1.1.1中有自动注入,1.2中取消了自动注入,需要手工注入,侵入性强  
    30.      * 也可在spring-mybatis.xml中如下配置,但是这种有多少个dao就要配置到多少个,多个dao就很麻烦。  
    31.      * <bean id="userDao"class="com.hua.saf.dao.UserDao">  
    32.      * <propertynamepropertyname="sqlSessionFactory" ref="sqlSessionFactory"/>  
    33.      * </bean>  
    34.      */  
    35.     @Resource  
    36.     public voidsetSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate){  
    37.        super.setSqlSessionTemplate(sqlSessionTemplate);  
    38.     }  
    39.      
    40. }  

    3>service服务

    1. packagecom.hys.app.student.service;  
    2. importorg.springframework.beans.factory.annotation.Autowired;  
    3. importorg.springframework.stereotype.Service;  
    4. importcom.hys.app.student.dao.StudentDaoImp;  
    5. importcom.hys.app.student.entity.Student;  
    6.    
    7. @Service  
    8. publicclass StudentService {  
    9.      
    10.     @Autowired  
    11.     private StudentDaoImp studentDaoImp;  
    12.      
    13.     public void save(Student student) {  
    14.        studentDaoImp.save(student);        
    15.     }  
    16.      
    17.     public Student getStudent(String id) {  
    18.        Student student =studentDaoImp.getStudent(id);  
    19.        return student;  
    20.     }  
    21.    
    22. }  

    四、采用接口org.apache.ibatis.session.SqlSession的实现类org.mybatis.spring.SqlSessionTemplate

    整体结构如下图:

    1、配置文件

    applicationContext02.xml

    1. <?xmlversionxmlversion="1.0"encoding="UTF-8"?>  
    2. <beansxmlns:xsibeansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"  
    3.   xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"  
    4.   xmlns:tx="http://www.springframework.org/schema/tx"xmlns:cache="http://www.springframework.org/schema/cache"  
    5.   xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans  
    6.      http://www.springframework.org/schema/beans/spring-beans.xsd  
    7.     http://www.springframework.org/schema/aop  
    8.     http://www.springframework.org/schema/aop/spring-aop.xsd  
    9.     http://www.springframework.org/schema/context  
    10.     http://www.springframework.org/schema/context/spring-context.xsd  
    11.     http://www.springframework.org/schema/tx  
    12.     http://www.springframework.org/schema/tx/spring-tx.xsd  
    13.     http://www.springframework.org/schema/cache  
    14.     http://www.springframework.org/schema/cache/spring-cache.xsd">  
    15.       
    16.     <!-- 自动扫描 -->  
    17.     <context:component-scanbase-packagecontext:component-scanbase-package="com.hys.app.**.service,com.hys.app.**.dao,com.hys.app.**.action"/>  
    18.     <!-- 引入外置文件 -->  
    19.     <beanidbeanid="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    20.         <propertynamepropertyname="location"value="classpath:jdbc.properties"/>  
    21.     </bean>  
    22.      
    23.     <!--数据库连接池配置-->  
    24.     <beanidbeanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">    
    25.        <propertynamepropertyname="driverClassName"value="${jdbc.driverClassName}"/>  
    26.        <propertynamepropertyname="url"value="${jdbc.url}"/>  
    27.        <propertynamepropertyname="username"value="${jdbc.username}"/>  
    28.         <propertynamepropertyname="password"value="${jdbc.password}"/>  
    29.     </bean>  
    30.    
    31.     <beannamebeanname="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">  
    32.       <propertynamepropertyname="dataSource"ref="dataSource"/>  
    33.       <propertynamepropertyname="mapperLocations"value="classpath:com/hys/app/**/dao/*.xml"/>  
    34.     </bean>  
    35.      
    36.     <!--  
    37.        Mybatis-Spring为我们提供了一个实现了SqlSession接口的SqlSessionTemplate类,它是线程安全的,可以被多个Dao同时使用。  
    38.        同时它还跟Spring的事务进行了关联,确保当前被使用的SqlSession是一个已经和Spring的事务进行绑定了的。  
    39.        而且它还可以自己管理Session的提交和关闭。当使用了Spring的事务管理机制后,SqlSession还可以跟着Spring的事务一起提交和回滚。  
    40.     -->  
    41.     <beanidbeanid="sqlSessionTemplate"class="org.mybatis.spring.SqlSessionTemplate">  
    42.         <constructor-argindexconstructor-argindex="0"ref="sqlSessionFactory"/>  
    43.     </bean>  
    44.        
    45. </beans>  

    studentMapper.xml

    1. <?xmlversionxmlversion="1.0"encoding="UTF-8"?>  
    2. <!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
    3.    
    4. <mappernamespacemappernamespace="com.hys.app.student.dao.StudentDao">  
    5.     <insertidinsertid="save"parameterType="com.hys.app.student.entity.Student">  
    6.         insert intot_app_student(id,name,sex,age) values(#{id},#{name},#{sex},#{age})  
    7.     </insert>  
    8.     <selectidselectid="getStudent"resultType="com.hys.app.student.entity.Student"parameterType="String">  
    9.         select * from t_app_student where id =#{id}  
    10.     </select>     
    11. </mapper>   

    2、创建action、service、dao、entity类

    1>dao接口

    1. package com.hys.app.student.dao;  
    2. import com.hys.app.student.entity.Student;  
    3.    
    4. public interface StudentDao {  
    5.     public void save(Student student);  
    6.     public Student getStudent(Stringid);  
    7. }  

    2>service服务

      1. packagecom.hys.app.student.service;  
      2. importorg.mybatis.spring.SqlSessionTemplate;  
      3. importorg.springframework.beans.factory.annotation.Autowired;  
      4. importorg.springframework.stereotype.Service;  
      5. importcom.hys.app.student.entity.Student;  
      6.    
      7. @Service  
      8. publicclass StudentService {  
      9.      
      10.     /**  
      11.      *sqlSessionTemplate模板提供了sqlsession  
      12.      */  
      13.      
      14.     @Autowired  
      15.     private SqlSessionTemplatesqlSessionTemplate;  
      16.      
      17.     public void save(Student student) {  
      18.        sqlSessionTemplate.insert("com.hys.app.student.dao.StudentDao.save",student);        
      19.     }  
      20.      
      21.     public Student getStudent(String id) {  
      22.        Student student =sqlSessionTemplate.selectOne("com.hys.app.student.dao.StudentDao.getStudent",id);  
      23.        return student;  
      24.     }  
      25.    
      26. }

    1、采用MapperScannerConfigurer,它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean。
    spring-mybatis.xml:

    复制代码
    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                            http://www.springframework.org/schema/context  
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                            http://www.springframework.org/schema/mvc  
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
        <!-- 自动扫描 -->
        <context:component-scan base-package="com.hua.saf" />
        <!-- 引入配置文件 -->
        <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location" value="classpath:jdbc.properties" />
        </bean>
    
        <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}" />
            <!-- 获取连接最大等待时间 -->
            <property name="maxWait" value="${maxWait}" />
        </bean>
    
        <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <!-- 自动扫描mapping.xml文件,**表示迭代查找 -->
            <property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" />
        </bean>
    
        <!-- DAO接口所在包名,Spring会自动查找其下的类 ,包下的类需要使用@MapperScan注解,否则容器注入会失败 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.hua.saf.*" />
            <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>
    复制代码
    复制代码

     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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
    例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)
    -->
    <mapper namespace="com.hua.saf.dao.UserDao">
      <!-- 
      在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复,
      使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
      resultType="com.hua.saf.User"就表示将查询结果封装成一个User类的对象返回,User类就是t_user表所对应的实体类
      -->
      <!-- 根据id查询得到一个user对象-->
      <select id="getUser" parameterType="int" resultType="com.hua.saf.pojo.User">
        select * from t_user where id=#{id}
      </select>
    </mapper>
    复制代码
    复制代码

    dao类:

    复制代码
    复制代码
    /** 
    * 这里的@MapperScan就是上面所讲的Mapper扫描器中所需要的配置,会自动生成代理对象。 
    * 注意,接口中的方法名称要和对应的MyBatis映射文件中的语句的id值一样,因为生成的 
    * 动态代理,会根据这个匹配相应的Sql语句执行。另外就是方法的参数和返回值也需要注 
    * 意。接口中的方法如何定义,对应的MyBatis映射文件就应该进行相应的定义。 
    * 最后,标注中的userDao是用来作为Spring的Bean的id(或name)进行使用的,方便我 
    * 们在Service层进行注入使用。 
    */ 
    
    @MapperScan
    public interface UserDao {
      //此处的方法名必须和mapper中的映射文件中的id同名
      //回去映射文件中通过com.hua.saf.dao.UserDao.getUser,即this.getClass().getName()+".getUser"
      public User getUser(int id);
    }
    复制代码
    复制代码

    service类:

    复制代码
    复制代码
    @Service("userService")
    public class UserServiceImpl implements IUserService {
    
    @Resource
    private UserDao userDao;
    
      public User getUser(int id) {
        return userDao.getUser(id);
      }
    }
    复制代码
    复制代码

     2、采用接口org.apache.ibatis.session.SqlSession的实现类org.mybatis.spring.SqlSessionTemplate。
      mybatis中, sessionFactory可由SqlSessionFactoryBuilder.来创建。MyBatis-Spring 中,使用了SqlSessionFactoryBean来替代。SqlSessionFactoryBean有一个必须属性dataSource,另外其还有一个通用属性configLocation(用来指定mybatis的xml配置文件路径)。
    spring-mybatis.xml

    复制代码
    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                            http://www.springframework.org/schema/context  
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                            http://www.springframework.org/schema/mvc  
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
        <!-- 自动扫描 -->
        <context:component-scan base-package="com.hua.saf" />
        <!-- 引入配置文件 -->
        <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location" value="classpath:jdbc.properties" />
        </bean>
    
        <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}" />
            <!-- 获取连接最大等待时间 -->
            <property name="maxWait" value="${maxWait}" />
        </bean>
    
        <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="configLocation"  value="classpath:sqlMapConfig.xml"/>
            <!-- 自动扫描mapping.xml文件,**表示迭代查找,也可在sqlMapConfig.xml中单独指定xml文件-->
            <property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" />
        </bean>
        
        <!-- mybatis spring sqlSessionTemplate,使用时直接让spring注入即可 -->
        <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
            <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
        </bean>
    
        <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>
    </beans>
    复制代码
    复制代码

    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>
            <typeAlias type="com.hua.saf.pojo.User" alias="User" />
        </typeAliases>
    </configuration>
    复制代码
    复制代码

    User.java

    复制代码
    复制代码
    public class User {
        
        private int id;
        private String username;
        private String password;
        private int age;
         
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
    }
    复制代码
    复制代码

    UserDao.java

    复制代码
    复制代码
    @Repository
    public class UserDao{
    
        @Resource
        private SqlSessionTemplate sqlSessionTemplate;
        
        public User getUser(int id) {
            return sqlSessionTemplate.selectOne(this.getClass().getName() + ".getUser", 1);
        }   
    }
    复制代码
    复制代码

    UserService.java

    复制代码
    复制代码
    @Service
    public class UserService{
        
        @Resource
        private UserDao userDao;
        
        public User getUser(int id) {
            return userDao.getUser(id);
        }
    }
    复制代码
    复制代码

    3、采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供SqlSession。
    spring-mybatis.xml

    复制代码
    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                            http://www.springframework.org/schema/context  
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                            http://www.springframework.org/schema/mvc  
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
        <!-- 自动扫描 -->
        <context:component-scan base-package="com.hua.saf" />
        <!-- 引入配置文件 -->
        <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location" value="classpath:jdbc.properties" />
        </bean>
    
        <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}" />
            <!-- 获取连接最大等待时间 -->
            <property name="maxWait" value="${maxWait}" />
        </bean>
    
        <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="configLocation"  value="classpath:sqlMapConfig.xml"/>
            <!-- 自动扫描mapping.xml文件,**表示迭代查找,也可在sqlMapConfig.xml中单独指定xml文件-->
            <property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" />
        </bean>
    
        <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>
    </beans>
    复制代码
    复制代码

    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>
            <typeAlias type="com.hua.saf.pojo.User" alias="User" />
        </typeAliases>
    </configuration>
    复制代码
    复制代码

    User.java

    复制代码
    复制代码
    public class User {
        
        private int id;
        private String username;
        private String password;
        private int age;
        
        
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
    }
    复制代码
    复制代码

    UserDao.java

    复制代码
    复制代码
    @Repository
    public class UserDao extends SqlSessionDaoSupport{
        
        public User getUser(int id) {
            return this.getSqlSession().selectOne(this.getClass().getName() + ".getUser", 1);
        }
      //使用SqlSessionDaoSupport必须注意,此处源码1.1.1中有自动注入,1.2中取消了自动注入,需要手工注入,侵入性强
      //也可在spring-mybatis.xml中如下配置,但是这种有多少个dao就要配置到少个,多个dao就很麻烦。
      //<bean id="userDao" class="com.hua.saf.dao.UserDao">
      //    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
      //</bean>
        @Resource
        public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
            // TODO Auto-generated method stub
            super.setSqlSessionFactory(sqlSessionFactory);
        }
    }
    复制代码
    复制代码

    UserService.java

    复制代码
    复制代码
    @Service
    public class UserService{
        
        @Resource
        private UserDao userDao;
        
        public User getUserss(int id) {
            return userDao.getUser(1);
        }
    }
  • 相关阅读:
    oracle数据库
    Filter过滤器
    Json
    监听器
    Ajax
    2018年5月14日java
    EL表达式&JSTL
    JSP
    2018年5月9日JAVA-servlet02
    如何解决写脚手架过程中遇到请求github的项目接口中出现API rate limit exceeded for的问题。
  • 原文地址:https://www.cnblogs.com/hanease/p/16244398.html
Copyright © 2020-2023  润新知