Mybatis学习(2):Mybatis和Spring整合详解

前言

Mybatis将一些琐碎的事交给Spring来处理,自身更加注重sql语句本身。

集成思路:

  • 需要spring来管理数据源信息。
  • 需要spring通过单例方式管理SqlSessionFactory。
  • 使用SqlSessionFactory创建SqlSession。(spring和mybatis整合自动完成)
  • 持久层的mapper都需要由spring进行管理,spring和mybatis整合生成mapper代理对象。

正文

一,集成步骤

  1. jar包集成;
  2. 配置文件集成(数据源);
  3. SqlSessionFactory集成;
  4. Mapper接口集成;

二,集成具体过程,以findUserById为例

1,环境准备以及项目结构

  • Jdk环境:jdk1.7.0_72
  • Ide环境:eclipse indigo
  • 数据库环境:MySQL 5.1
  • Mybatis:3.2.7
  • Spring:3.2.0
  • mybatis-spring.jar:整合jarbao

    Mybatis学习(2):Mybatis和Spring整合详解_第1张图片

2,数据库建表并编写实体类:User.class

CREATE TABLE `user4` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) ,
  `password` varchar(20) ,
  `age` int(11) ,
  PRIMARY KEY (`id`)
)
package com.jimmy.domain;

public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    // get,set方法略
}

3,Mybatis全局配置文件:SqlMapConfig.xml

全局配置文件已经没有数据库连接池配置啦,这些配置将在spring的配置文件中配置。



<configuration> 
    
    <mappers>
        <mapper resource="com/jimmy/dao/UserMapper.xml"/>
    mappers>
configuration>

4,Mybatis映射文件:UserMapper.xml

我们采用mapper开发,所以mapper接口和mapper.xml要一一对应。





<mapper namespace="com.jimmy.dao.UserMapper">
    <select id="findUserById" parameterType="int" resultType="com.jimmy.domain.User">
        select * from user4 where id = #{id}
    select>
    <select id="findUserAll" resultType="com.jimmy.domain.User">
        select * from user4 
    select>   
    <insert id="insertUser" parameterType="com.jimmy.domain.User">
        insert into user4(username,password,age) values(#{username},#{password},#{age})
    insert>
    <delete id="deleteUserById" parameterType="int">
        delete from user4 where id=#{id}
    delete>
    <update id="updateUserPassword" parameterType="com.jimmy.domain.User">
        update user4 set password=#{password} where id=#{id}
    update>
mapper>

5,编写DAO接口:UserMapper.java

package com.jimmy.dao;

import java.util.List;

import com.jimmy.domain.User;

public interface UserMapper {
    public User findUserById(int id);
    public List findUserAll();
    public void insertUser(User user);
    public void deleteUserById(int id);
    public void updateUserPassword(User user);
}

6,编写Spring核心配置文件:applicationContext.xml

  1. 首先配置数据库连接池
  2. 然后配置SqlSessionFactory
  3. 最后配置Mapper接口的代理类

最后配置mapper代理类还有2种情况,

  • 一种是每一个mapper接口都配置一个代理类,但是随着mapper接口增多,配置也会多。
  • 另一种是配置扫描包下的所有mapper接口,并批量创建代理对象。

先来看单个mapper代理类的配置:


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
                http://www.springframework.org/schema/beans 
                http://www.springframework.org/schema/beans/spring-beans.xsd">

        
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver">property>
            <property name="jdbcUrl" value="jdbc:mysql:///user">property>
            <property name="user" value="root">property>
            <property name="password" value="123456">property>    
        bean> 

        
        <bean id="sqlSessionFactoryId" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="configLocation" value="classpath:SqlMapConfig.xml">property>
            <property name="dataSource" ref="dataSource">property>
        bean>

        
        <bean id="singleMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
            <property name="mapperInterface" value="com.jimmy.dao.UserMapper">property>
            <property name="sqlSessionFactory" ref="sqlSessionFactoryId">property>
        bean>     
beans>

再来看批量创建mapper接口代理类的配置:


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
                http://www.springframework.org/schema/beans 
                http://www.springframework.org/schema/beans/spring-beans.xsd">

        
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver">property>
            <property name="jdbcUrl" value="jdbc:mysql:///user">property>
            <property name="user" value="root">property>
            <property name="password" value="123456">property>    
        bean> 

        
        <bean id="sqlSessionFactoryId" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="configLocation" value="classpath:SqlMapConfig.xml">property>
            <property name="dataSource" ref="dataSource">property>
        bean>

        
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.jimmy.dao">property>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryId">property>
        bean>     
beans>

7,写测试类

package com.jimmy.test;

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

import com.jimmy.dao.UserMapper;
import com.jimmy.domain.User;

public class Test1 {
    @Test
    public void testSingleMapper(){
        String springXML = "applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(springXML);

        UserMapper userMapper = (UserMapper) applicationContext.getBean("singleMapper");  //单mapper要引用id
        User user = userMapper.findUserById(9);
        System.out.println(user);

    }
    @Test
    public void testMultiMapper(){
        String springXML = "applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(springXML);

        UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper"); //批量mapper要引用“mapper接口名”,且首字母小写
        User user = userMapper.findUserById(9);
        System.out.println(user);
    }
}

至此,Mybatis和Spring的整合已经结束。

总结

接下来继续整合spring和springmvc。

你可能感兴趣的:(spring,mybatis,集成,整合,javaWeb,Mybatis)