美文网首页
spring和mybatis整合

spring和mybatis整合

作者: Stringer | 来源:发表于2016-11-27 21:49 被阅读17次

    整合思路

    需要spring通过单利方式管理sqlSessionFactory
    spring和mybatis整合生成代理对象,使用sqlSessionFactory创建sqlsession(自动完成)
    持久层mapper需要有spring进行管理

    创建新工程

    jar包:
    mybatis3.2.7
    spring3.2.0
    mybatis-spring-1.2.2(mybatis和spring的整合包)

    工程结构

    2016-11-26_133516.png

    Spring配置文件:
    在classpath下创建applicationContext.xml,定义数据库链接池、SqlSessionFactory
    applicationContext.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-3.2.xsd 
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
            
        <!-- 加载配置文件 -->
        <context:property-placeholder location="classpath:db.properties" />
            
        <!-- 数据源,使用dbcp 
            maxIdle,最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连
            接将被标记为不可用,然后被释放。设为0表示无限制。
            MaxActive,连接池的最大数据库连接数。设为0表示无限制。
            maxWait ,最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示
            无限制
        -->
        <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 
            在mybatis和spring的整合包中
        -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 加载mybatis的配置文件 -->
            <property name="configLocation" value="mybatis/SqlMapConfig.xml"/>
            <!-- 数据源 -->
            <property name="dataSource" ref="dataSource"/>
        </bean>
        
        <!-- 原始dao开发方法 -->
        <bean id="userDao" class="cn.ztc.ssm.dao.UserDaoImpl">
            <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
        </bean>
            
            
            
    </beans>```
    
    Mybatis配置文件
    在classpath下创建mybatis/SqlMapConfig.xml
    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>
    <settings>

    <setting name="lazyLoadingEnabled" value="true"/>

    <setting name="aggressiveLazyLoading" value="false"/>

    <setting name="cacheEnabled" value="true"/>
    </settings>

    <typeAliases>

        <!-- 批量别名的定义(常用)
            name:指定包名,Mybatis会自动扫描包中的po类。自动定义别名,别名就是类名,首字母大写小写都可
         -->
        <package name="cn.ztc.ssm.po"/>
    </typeAliases>
    
    <!-- 加载映射文件 -->
    <mappers>
        <mapper resource="sqlmap/User.xml"/>
        
        <!-- 批量加载 
            name:mapper接口的包名
        -->
        <package name="cn.ztc.ssm.mapper"/>
        
        
    </mappers>
    

    </configuration>

    
    原始的Dao开发
    
    Dao接口实现类继承SqlSessionDaoSupport
    使用此种方法即原始dao开发方法,需要编写dao接口,dao接口实现类、映射文件
    User.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="cn.ztc.ssm.po.User">
    select * from user where id = #{id}
    </select>

    </mapper>

    UserDao.java
    

    package cn.ztc.ssm.dao;

    import cn.ztc.ssm.po.*;

    public interface UserDao {

    //根据id查用户信息
    public User findUserById(int id) throws Exception;
    

    }

    UserDaoImpl.java
    

    package cn.ztc.ssm.dao;

    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.support.SqlSessionDaoSupport;

    import cn.ztc.ssm.po.*;

    public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{

    @Override
    public User findUserById(int id) throws Exception {
        //继承了SqlSessionDaoSupport,通过getSqlSession();方法得到sqlSession
        SqlSession sqlSession = this.getSqlSession();
        User user = sqlSession.selectOne("test.findUserById", id);
        //方法结束,自动关闭sqlSession
        //sqlSession.close();
        return user;
    }
    

    }

    测试类
    

    package cn.ztc.ssm.dao;

    import static org.junit.Assert.*;

    import org.junit.Before;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    import cn.ztc.ssm.po.User;

    public class UserDaoImplTest {

    private ApplicationContext applicationContext;
    
    //在setUp方法中得到spring的容器
    @Before
    public void setUp() throws Exception{
        applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
    }
    
    @Test
    public void testFindUserById() throws Exception {
        UserDao userDao = (UserDao) applicationContext.getBean("userDao");
        
        User user = userDao.findUserById(1);
        System.out.println(user);
    }
    

    }

    
    mapper代理开发
    
    UserMapper.java
    

    package cn.ztc.ssm.mapper;

    import java.util.List;

    import cn.ztc.ssm.po.User;
    import cn.ztc.ssm.po.UserCustom;
    import cn.ztc.ssm.po.UserQueryVo;

    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="cn.ztc.ssm.mapper.UserMapper">

    <select id="findUserById" parameterType="int" resultType="cn.ztc.ssm.po.User">
        select * from user where id = #{id}
    </select>
    

    </mapper>

    
    applicationContext.xml添加
    

    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">

    <property name="mapperInterface" value="cn.ztc.ssm.mapper.UserMapper"></property>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>```
    测试类

    package cn.ztc.ssm.mapper;
    
    import static org.junit.Assert.*;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import cn.ztc.ssm.po.User;
    
    public class UserMapperTest {
    
    private ApplicationContext applicationContext;
        
        //在setUp方法中得到spring的容器
        @Before
        public void setUp() throws Exception{
            applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
        }
        
        @Test
        public void testFindUserById() throws Exception {
            UserMapper usermapper = (UserMapper) applicationContext.getBean("userMapper");
            User user = usermapper.findUserById(1);
            System.out.println(user);
        }
    
    }
    

    此方法问题:要针对每个mapper配置
    解决方法:applicationContext.xml中添加

    <!-- mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并在spring容器中注册
            自动扫描出来的mapper的bean的id为mapper类名,首字母小写
         -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 指定扫描包名
                如果扫描多个包,每个包中间使用半角逗号分隔
                可删除sqlmapconfig.xml文件中的批量扫描配置
             -->
            
            <property name="basePackage" value="cn.ztc.ssm.mapper"/>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        </bean>
            ```

    相关文章

      网友评论

          本文标题:spring和mybatis整合

          本文链接:https://www.haomeiwen.com/subject/hefgpttx.html