myBatis与Spring整合

MyBatis数据库配置

实体类

用户:

package com.fuwenjun.entity;

public class User {
    private int id;
    private String name;
    private Dept dept;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Dept getDept() {
        return dept;
    }
    public void setDept(Dept dept) {
        this.dept = dept;
    }

}

用户对应系:

package com.fuwenjun.entity;
/**
 * 用户所在系别
 * @author 57231
 *
 */
public class Dept {
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
主要配置文件:
<?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>
    <properties resource="jdbc.properties"></properties>

    <!--设置别名  -->
    <!--默认引用哪个数据库环境  -->
     <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC">
            </transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
     </environments> 
    <!-- 加入所有的sql映射文件 -->
    <mappers>
        <!--第一种方式 ,用resource标签  -->
        <mapper resource="com/fuwenjun/dao/UserMapper.xml"/> 
    </mappers>
</configuration>

1.原始实现类方式
工具类:
SessionUtils:

package com.fuwenjun.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SessionUtlis {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;
    static{
        InputStream input;
        try {
            input = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(input);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
    public static SqlSession getSqlSession() {
        //线程中如果存在直接获取
        SqlSession sqlSession=threadLocal.get();
        if(sqlSession==null){
            sqlSession=sqlSessionFactory.openSession();
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }
    public static void closeSqlSession(){
        SqlSession sqlSession=threadLocal.get();
        if(sqlSession !=null){
            sqlSession.close();
            //分开当前线程与sqlsession对象的关系,目的是是gc尽早回收,不然会运行越来越慢
            threadLocal.remove();
        }
    }

}

UserDao

package com.fuwenjun.dao;

import org.apache.ibatis.session.SqlSession;

import com.fuwenjun.entity.User;
import com.fuwenjun.utils.SessionUtlis;

public class UserDao {
    //不涉及事务
    public User findById(int id){
        SqlSession sql=SessionUtlis.getSqlSession();
        User user=sql.selectOne("user.getUserById", 1);
        return user;
    }
}

UserMapper映射文件(原始dao实现): 如果需要改为Mapper接口实现那么
将namespace改为接口的完整类的路径
且有下面几个要求:
userMapper.xml 中 namespace 必须指定为接口类的全限定类名。
userMapper.xml 中 statement 的 id 指定为接口类中对应的方法名称。
userMapper.xml 中 statement 的输入参数类型和接口类中对应的方法参数类型一致。
userMapper.xml 中 statement 的返回类型和接口类中的对应方法的返回类型一致。

<?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.fuwenjun.dao.UserMapper">-->
<mapper namespace = "com.fuwenjun.dao.UserMapper"> 

    <!--
        1: id:表示一个sql句柄(相当于在jdbc的statement对象)
        2: paremeterType :输入参数的类型 ,在sql语句中,通过占位符#{}来接收此参数
        3:resultType: sql操作返回的结果类型
      -->
     <resultMap type="com.fuwenjun.entity.User" id="userMap">
        <id property="id" column="id"  />
        <result property="name" column="name"/>
        <result property="deptId" column="deptId"/></resultMap> 
    <select id = "getUserById" parameterType = "int" 
        resultMap = "userMap"   >
        select id,name
        from user
        where id=#{ 0 }
    </select>
    <!--查询所有用户信息  -->  
    <select id = "getUserList" resultMap="userMap">
        select id,name,deptId
        from user
    </select>

</mapper>

Mybatis与Spring集成:
引入整合的包:mybatis-Spring-1.2.4.jar
1)配置管理SQLSessionFactory
2)配置管理数据源
3)配置管理Mapper对象
数据库连接交给Spring 所以在mybatis配置中清除数据连接
一.接口与类的整合

<?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>

    <mappers>
        <!--第一种方式 ,用resource标签  -->
        <mapper resource="com/fuwenjun/dao/UserMapper.xml"/> 
        <mapper resource="com/fuwenjun/dao/DeptMapper.xml"/> 
    </mappers>
</configuration>

在数据库中增加数据库连接

<?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:context="http://www.springframework.org/schema/context"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xmlns:tx="http://www.springframework.org/schema/tx"
      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.0.xsd

      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd

      http://www.springframework.org/schema/aop 
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

      ">

    <context:component-scan base-package="com.fuwenjun" />

    <context:property-placeholder location = "classpath:jdbc.properties"/>

    <bean id= "dataSource" 
            class= "com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>    
        <property name="jdbcUrl" value="${jdbc.url}"></property>       
        <property name="user" value="${jdbc.user}"></property>     
        <property name="password" value="${jdbc.password}"></property>                     
    </bean> 

        <!--注册事务管理器  -->
         <!-- 配置事务管理 -->  
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource"/>  
    </bean> 

     <tx:advice id="transactionAdvice" transaction-manager="transactionManager">    
        <tx:attributes>    
            <tx:method name="delete*" propagation="REQUIRED" />    
            <tx:method name="save*" propagation="REQUIRED" />    
            <tx:method name="update*" propagation="REQUIRED" />    
            <tx:method name="find*" read-only="true" />    
            <tx:method name="get*" read-only="true" />    
            <tx:method name="select*" read-only="true" />    
        </tx:attributes>    
    </tx:advice>   
      <aop:config>    
        <!-- 第一个"*"代表所有类, 第二个"*"代表所有方法, ".."代表任意参数    --> 
     <aop:pointcut id="pointcut" expression="execution(* com.fuwenjun.service.*.*(..))" />    

       <!--  把事务控制在service层     -->
        <aop:advisor pointcut-ref="pointcut" advice-ref="transactionAdvice" />    
    </aop:config>   
    <!--开启事务的注解驱动  -->
    <tx:annotation-driven transaction-manager="transactionAdvice"/> 

    <!--配置mybatis的sqlSessionFactory  -->
    <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref = "dataSource"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>    
    </bean>
    <bean id="userDao" class="com.fuwenjun.dao.UserDao">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>
    <bean id="userService" class="com.fuwenjun.service.UserService">
        <property name="userDao" ref="userDao"></property>
    </bean>
</beans>        

二.mapper动态代理整合
修改spring配置

<?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:context="http://www.springframework.org/schema/context"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xmlns:tx="http://www.springframework.org/schema/tx"
      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.0.xsd

      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd

      http://www.springframework.org/schema/aop 
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

      ">

    <context:component-scan base-package="com.fuwenjun" />

    <context:property-placeholder location = "classpath:jdbc.properties"/>

    <bean id= "dataSource" 
            class= "com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>    
        <property name="jdbcUrl" value="${jdbc.url}"></property>       
        <property name="user" value="${jdbc.user}"></property>     
        <property name="password" value="${jdbc.password}"></property>                     
    </bean> 

    <!--注册事务管理器  -->
    <bean id = "txMgr" 
        class = "org.springframework.jdbc.datasource.DataSourceTransactionManager" >    
        <property name="dataSource" ref = "dataSource"></property>
    </bean>     

    <!--开启事务的注解驱动  -->
    <tx:annotation-driven transaction-manager="txMgr"/> 

    <!--配置mybatis的sqlSessionFactory  -->
    <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref = "dataSource"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>    
    </bean>
    <!--***基于动态代理的mapper注入方式,之后在service中直接注入userMapper接口***-->
    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean" >
        <property name="mapperInterface" value="com.fuwenjun.dao.UserMapper"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>
    <bean id="userService" class="com.fuwenjun.service.UserService">
        <property name="userMapper" ref="userMapper"></property>
    </bean>
</beans>         

Mybatis配置文件也需要更改:
Mapper映射配置需要对应到具体Mapper接口的类建议直接扫描所在包

    <package name="com.fuwenjun.dao"/>
        <!--第一种方式 ,用resource标签 
        <!-- <mapper resource="com/fuwenjun/dao/UserMapper.xml"/> --> 
        <!-- 第二种方式 使用class标签引用接口类,规则接口类需要与SQL映射文件同名,然后在同一路径
            <mapper class="com.fuwenjun.dao.UserMapper"> -->
        <!-- 第三种方式:使用package包名扫描所在路径的所有mapper接口,规则与第二种方式相同-->
                <package name="com.fuwenjun.dao"/>

事务的管理:
与spring整合之后事务交给spring管理,在spring中控制事务;增加Spring的配置文件如下:

    <!--注册事务管理器  -->
         <!-- 配置事务管理 -->  
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource"/>  
    </bean> 

     <tx:advice id="transactionAdvice" transaction-manager="transactionManager">    
        <tx:attributes>    
            <tx:method name="delete*" propagation="REQUIRED" />    
            <tx:method name="save*" propagation="REQUIRED" />    
            <tx:method name="update*" propagation="REQUIRED" />    
            <tx:method name="find*" read-only="true" />    
            <tx:method name="get*" read-only="true" />    
            <tx:method name="select*" read-only="true" />    
        </tx:attributes>    
    </tx:advice>   
      <aop:config>    
        <!-- 第一个"*"代表所有类, 第二个"*"代表所有方法, ".."代表任意参数    --> 
     <aop:pointcut id="pointcut" expression="execution(* com.fuwenjun.service.*.*(..))" />    

       <!--  把事务控制在service层     -->
        <aop:advisor pointcut-ref="pointcut" advice-ref="transactionAdvice" />    
    </aop:config>   
    <!--开启事务的注解驱动::未测试注解的方式  -->
    <tx:annotation-driven transaction-manager="transactionAdvice"/> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值