Mybatis和Spring整合


一、dao接口+實現類的方式

  1、先創建好整合工程結構

  

  2、對於Spring和Mybatis 整合,我們先從數據庫開始,即先創建一張簡單的數據表,Sql如下

CREATE TABLE `t_user` (
  `id` INT(10) NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(100) DEFAULT NULL,
  `password` VARCHAR(100) DEFAULT NULL,
  `address` VARCHAR(100) DEFAULT NULL,
  `sex` VARCHAR(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8

  然后根據從上面的數據表創建對應的實體類

 1 package cn.test.ssm.po;
 2 
 3 import java.io.Serializable;
 4 
 5 public class User implements Serializable {
 6     private int id;
 7     private String username;
 8     private String password;
 9     private String address;
10     private String sex;
11 
12     public int getId() {
13         return id;
14     }
15 
16     public String getUsername() {
17         return username;
18     }
19 
20     public String getPassword() {
21         return password;
22     }
23 
24     public String getAddress() {
25         return address;
26     }
27 
28     public String getSex() {
29         return sex;
30     }
31 
32     public void setId(int id) {
33         this.id = id;
34     }
35 
36     public void setUsername(String username) {
37         this.username = username;
38     }
39 
40     public void setPassword(String password) {
41         this.password = password;
42     }
43 
44     public void setAddress(String address) {
45         this.address = address;
46     }
47 
48     public void setSex(String sex) {
49         this.sex = sex;
50     }
51 
52     public User(String username, String password, String address, String sex) {
53         this.username = username;
54         this.password = password;
55         this.address = address;
56         this.sex = sex;
57     }
58 
59     public User() {
60     }
61 
62     @Override
63     public String toString() {
64         return "User{" +
65                 "id=" + id +
66                 ", username='" + username + '\'' +
67                 ", password='" + password + '\'' +
68                 ", address='" + address + '\'' +
69                 ", sex='" + sex + '\'' +
70                 '}';
71     }
72 }
User

  3、然后我們開始配置Mybatis的相關配置文件,具體有Mybatis的核心配置文件SqlMapConfig.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6 
 7     <typeAliases>
 8         <!--批量別名定義:Mybatis在定義別名的時候會自動掃描包中的po類,自動的將別名定義為類名(首字母大寫或者小寫都可以)-->
 9         <package name="cn.test.ssm.po"></package>
10     </typeAliases>
11 
12     <!--配置一個SQL語句和映射的配置文件-->
13     <mappers>
14         <mapper resource="sqlmap/UserMapper.xml" />
15     </mappers>
16 
17 </configuration>

  然后就是配置UserMapper.xml映射文件,由於只是測試Spring和Mybatis的整合,所以可以只是實現相對簡單的功能,這樣的話,UserMapper配置文件也就比較簡單

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <!--mapper為根元素,namespace指定了命名空間-->
 6 <mapper namespace="test">
 7 
 8     <select id="findUserById" parameterType="int" resultType="cn.test.ssm.po.User">
 9         SELECT * FROM t_user WHERE id = #{id}
10     </select>
11 
12 </mapper>

  4、下來就是根據UserMapper中的statment實現的功能,寫dao接口文件

1 package cn.test.ssm.dao;
2 
3 import cn.test.ssm.po.User;
4 
5 public interface UserDao {
6 
7     public User findUserById(int id) throws Exception;
8 }

  5、我們編寫dao接口的實現類。在dao接口的實現類過程中,我們需要知道,由於Spring整合Mybatis的原因,Spring需要管理SqlSessionFactory,而實現類方法中需要得到這個SqlSessionFactory,這里我們可以繼承SqlSessionDaoSupport這個類,我們看一下這個類中的方法

 

  6、下來我們就具體的配置applicationContext配置文件,其中需要配置數據庫信息,加載其他的配置文件,管理配置SqlSessionFactory(要加載Mybatis核心配置文件),然后我們管理UserDao接口的bean,同上面分析的,就需要配置SqlSessionFactory這個屬性

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:aop="http://www.springframework.org/schema/aop"
 6        xmlns:tx="http://www.springframework.org/schema/tx"
 7        xsi:schemaLocation="
 8         http://www.springframework.org/schema/beans
 9         http://www.springframework.org/schema/beans/spring-beans.xsd
10         http://www.springframework.org/schema/aop
11         http://www.springframework.org/schema/aop/spring-aop.xsd
12         http://www.springframework.org/schema/context
13         http://www.springframework.org/schema/context/spring-context.xsd
14         http://www.springframework.org/schema/tx
15         http://www.springframework.org/schema/tx/spring-tx.xsd">
16 
17 
18     <!--加載數據庫信息的配置文件-->
19     <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
20 
21     <!--配置數據源-->
22     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
23         <property name="driverClass" value="${jdbc.driver}" />
24         <property name="jdbcUrl" value="${jdbc.url}" />
25         <property name="user" value="${jdbc.username}" />
26         <property name="password" value="${jdbc.password}" />
27     </bean>
28 
29     <!--配置SqlSessionFactory-->
30     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
31         <!--加載Mybatis的配置文件-->
32         <property name="configLocation" value="mybatis/SqlMapConfig.xml"></property>
33         <!--配置數據源-->
34         <property name="dataSource" ref="dataSource"></property>
35     </bean>
36 
37     <!--配置Dao接口-->
38     <bean id="userDao" class="cn.test.ssm.dao.UserDaoImpl">
39         <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
40     </bean>
41 </beans>

   7、編寫好applicationContext之后,就開始實現UserDao這個接口,也是如同上面的分析,實現SqlSessionDaoSupport這個抽象類,從而得到SqlSessionFactory,在方法體內獲取SqlSession

 1 package cn.test.ssm.dao;
 2 
 3 import cn.test.ssm.po.User;
 4 import org.apache.ibatis.session.SqlSession;
 5 import org.mybatis.spring.support.SqlSessionDaoSupport;
 6 
 7 public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{
 8 
 9 //    SqlSessionDaoSupport中有 public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) 方法
10 
11     @Override
12     public User findUserById(int id) throws Exception {
13         SqlSession sqlSession = getSqlSession(); //SqlSessionDaoSupport中有private SqlSession sqlSession;這個屬性和方法
14         User user = sqlSession.selectOne("test.findUserById",1);
15         //使用spring來記性管理,在方法結束的時候就會自己關閉SqlSession
16         return user;
17     }
18 }

  8、編寫相應的Junit進行測試 

 1 package cn.test.ssm.dao;
 2 
 3 import cn.test.ssm.po.User;
 4 import org.apache.ibatis.session.SqlSession;
 5 import org.mybatis.spring.support.SqlSessionDaoSupport;
 6 
 7 public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{
 8 
 9 //    SqlSessionDaoSupport中有 public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) 方法
10 
11     @Override
12     public User findUserById(int id) throws Exception {
13         SqlSession sqlSession = getSqlSession(); //SqlSessionDaoSupport中有private SqlSession sqlSession;這個屬性和方法
14         User user = sqlSession.selectOne("test.findUserById",1);
15         //使用spring來記性管理,在方法結束的時候就會自己關閉SqlSession
16         return user;
17     }
18 }

  通過上面的測試程序得到結果

二、通過mapper代理方式

   1、mapper代理的方式進行整合,其實跟第一篇中講到的差不多,實際上比較重要的就是mapper接口和mapper配置文件在同一包下,且文件名相同即可,下面是使用mapper代理的方式的結構

  

  2、然后我么來配置UserMapper配置文件,需要注意的就是這個配置文件中需要將namespace設置為Mapper接口的路徑

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <!--mapper為根元素,namespace指定了命名空間-->
 6 <mapper namespace="cn.test.ssm.mapper.UserMapper">
 7 
 8     <select id="findUserById" parameterType="int" resultType="cn.test.ssm.po.User">
 9         SELECT * FROM t_user WHERE id = #{id}
10     </select>
11 
12 </mapper>

  3、然后我們配置applicationContext配置文件,這里介紹兩種配置,一種是單個Mapper的配置,一種的進行包掃描的配置

  ①單個Mapper的配置

    a)其中需要配置的就是MapperInterface接口和SqlSessionFactory兩個屬性,MapperInterface作用就是掃描指定的Mapper接口文件

    <!--配置mapper
    通過MapperFactoryBean來進行配置,該類能夠根據mapper接口生成代理對象
    -->
    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <!--配置mapper接口-->
        <property name="mapperInterface" value="cn.test.ssm.mapper.UserMapper"></property>
        <!--配置SqlSessionFactory-->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

    b)使用測試程序進行測試

 1 package test;
 2 
 3 import cn.test.ssm.dao.UserDao;
 4 import cn.test.ssm.mapper.UserMapper;
 5 import cn.test.ssm.po.User;
 6 import org.junit.Before;
 7 import org.junit.Test;
 8 import org.springframework.context.ApplicationContext;
 9 import org.springframework.context.support.ClassPathXmlApplicationContext;
10 
11 import static org.junit.Assert.*;
12 
13 public class UserMapperTest {
14     private ApplicationContext applicationContext;
15 
16     @Before
17     public void setUp() throws Exception {
18         //得到spring的容器
19         applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
20     }
21 
22     @Test
23     public void findUserById() throws Exception{
24         UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
25 
26         User user = userMapper.findUserById(1);
27 
28         System.out.println(user);
29     }
30 }

  c)通過觀察日志分析結果如下:

   ②通過掃描mapper包的方式進行配置

    a)其中basePackage就是設置掃描的包,當有多個包需要掃描的時候,使用逗號隔開

1     <!--通過配置掃描器的方式解決上面配置存在的不足:當我們的Mapper接口比較多的時候,上面單個配置Mapper顯然會比較繁瑣,
2         所以我們可以使用掃描器的方式進行配置,將mapper包下面的所有接口同時進行掃描配置,顯然,mapper接口的文件名和Mapper
3         配置文件的文件名應該相同
4     -->
5     <!--通過下面的這種配置:可以自動創建對象並且向spring容器中注入-->
6     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
7         <property name="basePackage" value="cn.test.ssm.mapper"></property>
8         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
9     </bean>

     b)測試程序和上面的測試程序相同,我們來運行測試程序,但是發現運行出了下面的異常

    c)通過查詢資料,發現是由於Spring版本和Jdk版本不支持的原因,因為本次測試使用的Spring版本是3.2.x,然后該版本不支持jdk1.8,所以就需要修改jdk版本為1.7,如下圖所示

   

  然后再次運行項目即可

   

 

 

 


免責聲明!

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



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