31Mybatis_mybatis和spring整合-mapper代理开发

案例结构图:

cn.itcast.ssm.mapper:存放mapper接口以及mapper.xml代码。

cn.itcast.ssm.po:存放数据库实体类。

config:存放各种配置文件。

test:存放测试代码。

OrdersMapperCustom.java代码如下:

package cn.itcast.ssm.mapper;


import cn.itcast.ssm.po.User;




public interface OrdersMapperCustom {
    //函数的名字OrdersMapperCustom.xml中select中的id名一样
    
     public User  finduserByid(int id);
}

ordersMapperCustom.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">
<!-- nanmespace:命名空间。 作用就是对sql进行分类话管理,理解Sal分离

注意:使用mapper代理方式,namespace有特殊重要的作用
-->

<mapper namespace="cn.itcast.ssm.mapper.OrdersMapperCustom">
  <cache></cache>
 
     
     
     <select id="finduserByid" parameterType="int" resultType="cn.itcast.ssm.po.User">
         SELECT * FROM USER WHERE ID=#{VALUE}
     </select>
     
 
      
      
</mapper>

User.java代码如下:

package cn.itcast.ssm.po;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class User implements Serializable {
private int id;//对应数据库中主键
private String username;//对应数据库中用户的名称
private Date birthday;//对应数据库中的生日
private String sex;//性别
private String address;//地址



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 Date getBirthday() {
    return birthday;
}
public void setBirthday(Date birthday) {
    this.birthday = birthday;
}
public String getSex() {
    return sex;
}
public void setSex(String sex) {
    this.sex = sex;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

}

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>
    
    <!-- 用包加载的方式进sqlMapConfig.xml-->
        <mappers>
            <mapper class="cn.itcast.ssm.mapper.OrdersMapperCustom"/>
            
         </mappers>
    
    
    
</configuration>

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" />
   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
       <property name="driverClassName" value="${jdbc.driver}"></property>
       <property name="url" value="${jdbc.url}"></property>
       <property name="password" value="${jdbc.password}"></property>
       <property name="username" value="${jdbc.username}"></property>
       <property name="maxActive" value="10"></property>
       <property name="maxIdle" value="5"></property>
   </bean>
   <bean  id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <property name="configLocation" value="mybatis/SqlMapConfig.xml"></property>
       <!-- 配置数据源 -->
       <property name="dataSource" ref="dataSource"></property>
   </bean>
    
   <bean id="OrdersMapperCustom" class="org.mybatis.spring.mapper.MapperFactoryBean">
     <!-- 给org.mybatis.spring.mapper.MapperFactoryBean类中一些
     属性赋值:
     1:生成Mapper是需要sqlSession的,而生成sqlSession是需要sqlSessionFactory的。所以配置了
            <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
     2: 生成Mapper代理对象是需要Mapper类类型的。所以这句话就是指定类型 <property name="mapperInterface" value="cn.itcast.ssm.mapper.OrdersMapperCustom"></property>      
              意思是根据cn.itcast.ssm.mapper.OrdersMapperCustom这个接口创建Mapper代理类。
      -->
       <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
      <property  name="mapperInterface" value="cn.itcast.ssm.mapper.OrdersMapperCustom"></property>
   </bean>


</beans>

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">
<!-- nanmespace:命名空间。 作用就是对sql进行分类话管理,理解Sql分离

注意:使用mapper代理方式,namespace有特殊重要的作用
-->

<mapper namespace="test">
    
    <!-- 根据id获取用户信息 -->
    <!-- 在映射文件中配置很多sql语句 -->
    <!-- 
    id:标识映射文件中的sql;
    将sql语句封装到mappedStatement对象中,所以将id称为statement的id;parmenterType:指定输入的参数的类型,这里指定的int型
    #{}表示一个占位符号;
    #{id}:其中的id表示接收输入的参数,参数名称就是id,如果输入参数就是简单类型,#{}中的参数名可以任意,可以value或其它名称
    resultType:指定的sql输出结果的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象;
    
     -->
    <select id="findUserById" parameterType="int" resultType="cn.itcast.ssm.po.User">
        select * from user where id = #{id}
    </select>
    

    

   
</mapper>

db.properties代码如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybaits
jdbc.username=root
jdbc.password=root

log4j.properties:

# Global logging configuration
#u5728u5f00u53d1u73afu5883u4e0bu65e5u5fd7u7ea7u522bu8981u8bbeu7f6eu6210DEBUGuff0cu751fu4ea7u73afu5883u8bbeu7f6eu6210infou6216error
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

Junit测试代码:TestSprigMybatis:

package springmvc_mybatis_shen;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.ssm.Dao.UserDao;
import cn.itcast.ssm.mapper.OrdersMapperCustom;

public class TestSpringMybatis {
    ApplicationContext applicationContext;
    @Before
    public void setup()
    {//spring的方式加载配置文件
        applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
        
        
    }
    @Test
    public void testSpringMyabtis()
    {OrdersMapperCustom ordersMapperCustom=(OrdersMapperCustom) applicationContext.getBean("OrdersMapperCustom");
     ordersMapperCustom.finduserByid(1);
        
        
    }

}

运行结果:正确

------------------------------------------------------------------------------------------------------------------------------------------------

但是上面的applicationContext.xml(如下)代码写的繁琐

   <bean id="OrdersMapperCustom" class="org.mybatis.spring.mapper.MapperFactoryBean">
     <!-- 给org.mybatis.spring.mapper.MapperFactoryBean类中一些
     属性赋值:
     1:生成Mapper是需要sqlSession的,而生成sqlSession是需要sqlSessionFactory的。所以配置了
            <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
     2: 生成Mapper代理对象是需要Mapper类类型的。所以这句话就是指定类型 <property name="mapperInterface" value="cn.itcast.ssm.mapper.OrdersMapperCustom"></property>      
              意思是根据cn.itcast.ssm.mapper.OrdersMapperCustom这个接口创建Mapper代理类。
      -->
       <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
      <property  name="mapperInterface" value="cn.itcast.ssm.mapper.OrdersMapperCustom"></property>
   </bean>

:需要对每个mapper进行配置,麻烦。

所以工作中的做法是:

  通过MapperScannerConfigurer进行mapper扫描(建议使用)

针对上面的案例,此处只要修改三处代码:

1.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" />
   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
       <property name="driverClassName" value="${jdbc.driver}"></property>
       <property name="url" value="${jdbc.url}"></property>
       <property name="password" value="${jdbc.password}"></property>
       <property name="username" value="${jdbc.username}"></property>
       <property name="maxActive" value="10"></property>
       <property name="maxIdle" value="5"></property>
   </bean>
   <bean  id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <property name="configLocation" value="mybatis/SqlMapConfig.xml"></property>
       <!-- 配置数据源 -->
       <property name="dataSource" ref="dataSource"></property>
   </bean>
    

   
   
   
   <!-- mapper批量扫描:从mapper包中扫面出mapper接口,自动创建代理对象并且在spring
   容器中注册遵循规范,将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中
   自动扫面出来的mapper的bean的id为mapper类名(首字母小写)。
   
   用这种做法的话在SqlMapConfig.xml中加载OrdersMapperCustom.xml的代码
   ( <mapper class="cn.itcast.ssm.mapper.OrdersMapperCustom"/>)就可以去掉。
    
   
   
    -->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <!-- 
       
       如果扫描多个包,每个包中间使用半角逗号分隔
       
        -->
       <property name="basePackage" value="cn.itcast.ssm.mapper"></property>
       
       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
   </bean>


</beans>

2.SqlMapConfig.xml代码:这里不需要再写 <mapper class="cn.itcast.ssm.mapper.OrdersMapperCustom"/>

代码了,因为在applicationContext.xml的 mapper批量扫描会自动去加载

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

3.

package springmvc_mybatis_shen;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.ssm.Dao.UserDao;
import cn.itcast.ssm.mapper.OrdersMapperCustom;

public class TestSpringMybatis {
    ApplicationContext applicationContext;
    @Before
    public void setup()
    {//spring的方式加载配置文件
        applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
    }
    @Test
    public void testSpringMyabtis()
    {
        /*
         * 将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中。
                              自动扫面出来的mapper的bean的id为mapper类名(首字母小写)也就是ordersMapperCustom。
         * 
         */
        OrdersMapperCustom ordersMapperCustom=(OrdersMapperCustom) applicationContext.getBean("ordersMapperCustom");
     ordersMapperCustom.finduserByid(1);
        
        
    }

}

运行结果:一切正常。

原文地址:https://www.cnblogs.com/shenxiaoquan/p/5800068.html