Home  >  Article  >  Java  >  Spring+SpringMVC+MyBatis in-depth learning and construction-MyBatis and Spring integration

Spring+SpringMVC+MyBatis in-depth learning and construction-MyBatis and Spring integration

巴扎黑
巴扎黑Original
2017-06-26 09:26:261556browse

Please indicate the source for reprinting:

As mentioned earlier: Spring+SpringMVC+MyBatis in-depth learning and construction (8)-MyBatis query cache

1. Integration ideas

Spring is required to manage SqlSessionFactory through a single instance.

Spring and MyBatis integrate to generate proxy objects, and use SqlSessionFactory to create SqlSession. (The integration of Spring and MyBatis is automatically completed)

The mappers of the persistence layer need to be managed by Spring.

2. Integrated environment

Create a java project (close to the actual development project structure)

jar package:

mybatis3.2.7 jar package

jar package of spring3.2.0

dbcp connection pool

Database driver

Integration package of mybatis and spring: The early integration of ibatis and spring was officially launched by spring Provided, mybatis and spring integration are provided by mybatis.

3.spring configuration file

Configure sqlSessionFactory and data source in applicationContext.xml. SqlSessionFactory is under the integration package of mybatis and spring.


<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 
         
         
         
         
         
         
         
         
         "><!-- 加载配置文件 --><context:property-placeholder location="classpath:db.properties"/><!-- 数据库连接池,使用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配置 --><!-- 让Spring管理SqlSessionFactory使用mybatis和spring整合包中的 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 数据库连接池 --><property name="dataSource" ref="dataSource" /><!-- 加载mybatis的全局配置文件 --><property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /></bean></beans>

4. Three methods written by Mapper

4.1 Original dao development (after integration with spring)

4.1.1User. 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"><!--namespace命名空间,作用就是对sql进行分类化的管理,理解为sql隔离
    注意:使用mapper代理开发时,namespace有特殊作用  --><mapper namespace="test"><!--在映射文件中配置很多sql语句  --><!--需求:通过id查询用户表的记录  --><!--id:标识映射文件中的sql,称为statement的id。将sql语句封装在mapperStatement的对象中,所有id称为Statement的id;
        parameterType:指定输入参数的类型,这里指定int型;
        #{}:表示一个占位符;
        #{id}:其中id表示接收输入的参数,参数名称就是id,如果输入参数是简单类型,#{}中的参数名可以任意,可以是value或其它名称;
        resultType:指定输出结果所映射的Java对象类型,select指定resultType表示将单条记录映射成Java对象。      --><select id="findUserById" parameterType="int" resultType="joanna.yan.po.User">select * from user where id=#{value}</select> </mapper>

Load User.xml in 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>  <!-- 
      批量别名的定义:
      package:指定包名,mybatis会自动扫描包中的pojo类,自定义别名,别名就是类名(首字母大写或小写都可以) -->  <typeAliases>  <package name="joanna.yan.po"/>  </typeAliases><mappers><mapper resource="sqlmap/User.xml"/><!-- 批量加载映射配置文件,mybatis自动扫描包下的mapper接口进行加载;
            遵循一定的规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录中;
            以上规范的前提是:使用的是mapper代理方法;          --><package name="joanna.yan.mapper"/></mappers>
 </configuration>

4.1.2 dao (implement class inheritance SqlSessionDaoSupport)


public interface UserDao {//根据id查询用户信息public User findUserById(int id) throws Exception;
}

dao interface implementation class needs to inject SqlSessionFactory through spring.

The spring declaration configuration method is used here to configure the dao bean: Let the UserDaoImpl implementation class inherit SqlSessionDaoSupport.


public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{

    @Overridepublic User findUserById(int id) throws Exception {//继承SqlSessionDaoSupport,通过this.getSqlSession()得到sqlSessionSqlSession sqlSession=this.getSqlSession();
        User user=sqlSession.selectOne("test.findUserById", id);return user;
    }
}

4.1.3 Configure dao

Configure dao in applicationContext.xml.


    <!-- 方法一:原始dao接口  --><bean id="userDao" class="joanna.yan.dao.UserDaoImpl"><property name="sqlSessionFactory" ref="sqlSessionFactory" /></bean>

4.1.4 Test program


public class UserDaoImplTest {private ApplicationContext applicationContext;
    
    @Beforepublic void setUp(){
        applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
    }
    
    @Testpublic void findUsetByIdTest() throws Exception{
        UserDao userDao=(UserDao) applicationContext.getBean("userDao");
        User user=userDao.findUserById(1);
        System.out.println(user);
    }
}

4.2mapper agent development

4.2.1mapper .xml and mapper.java


##

<?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"><!--namespace命名空间,作用就是对sql进行分类化的管理,理解为sql隔离
    注意:使用mapper代理开发时,namespace有特殊作用,namespace等于mapper接口地址  --><mapper namespace="joanna.yan.mapper.UserMapper"><select id="findUserById" parameterType="int" resultType="user">select * from user where id=#{value}</select></mapper>


public interface UserMapper {public User findUserById(int id) throws Exception;
}
4.2.2 Create proxy object through MapperFactoryBean

Configure mapper in applicationContext.xml.


    <!-- 方法二:mapper配置
         MapperFactoryBean:根据mapper接口生成代理对象     --><bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"><property name="mapperInterface" value="joanna.yan.mapper.UserMapper" /><property name="sqlSessionFactory" ref="sqlSessionFactory" /></bean>
4.2.3 Test program


public class UserMapperTest {private ApplicationContext applicationContext;
    
    @Beforepublic void setUp(){
        applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
    }
    
    @Testpublic void findUsetByIdTest() throws Exception{
        UserMapper userMapper=(UserMapper) applicationContext.getBean("userMapper");
        User user=userMapper.findUserById(1);
        System.out.println(user);
    }
}
The problem with this method: it needs to be configured for each mapper. trouble.

4.3 Mapper scanning through MapperScannerConfigurer (recommended)

Configure mapper batch scanning in applicationContext.xml.


    <!-- 方法三:mapper批量扫描 
          从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册
          遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中。
         自动扫描出来的mapper的bean的id为mapper类名(首字母小写)     --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 指定扫描的包名
             如果扫描多个包,每个包中间使用半角逗号分隔          --><property name="basePackage" value="joanna.yan.mapper"/><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/></bean>
At this time, the configuration of mapper for batch loading joanna.yan.mapper in SqlMapConfig.xml can be omitted.

Test procedure:


@Testpublic void findUsetByIdTest() throws Exception{
        UserMapper userMapper=(UserMapper) applicationContext.getBean("userMapper");
        User user=userMapper.findUserById(1);
        System.out.println(user);
    }

The above is the detailed content of Spring+SpringMVC+MyBatis in-depth learning and construction-MyBatis and Spring integration. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn