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
#\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216error
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);
        
        
    }

}

運行結果:一切正常。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM