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

本文详细介绍MyBatis与Spring框架的集成步骤及过程,包括环境搭建、配置文件编写、接口映射等,并提供测试代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

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

    这里写图片描述

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的配置文件中配置。

<?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> 
    <!-- 如果mapper.xml和mapper.java接口在同一个目录,此处也可不用定义mappers -->
    <mappers>
        <mapper resource="com/jimmy/dao/UserMapper.xml"/>
    </mappers>
</configuration>

4,Mybatis映射文件:UserMapper.xml

我们采用mapper开发,所以mapper接口和mapper.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">

<!-- mapper标签要指定namespace属性,不然会报错,且mapper开发时设置为Mapper接口的全限定名-->
<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<User> 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代理类的配置:

<?xml version="1.0" encoding="UTF-8"?>
<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">

        <!--1, 数据库连接的操作交给spring -->
        <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> 

        <!--2,配置mybatis的SqlSessionFactory,需要注入全局配置文件和连接池  -->
        <bean id="sqlSessionFactoryId" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
            <property name="dataSource" ref="dataSource"></property>
        </bean>

        <!--3, 配置单mapper代理开发模式,通过id名获得mapper类对象,进而调用函数  -->
        <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接口代理类的配置:

<?xml version="1.0" encoding="UTF-8"?>
<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">

        <!--1, 数据库连接的操作交给spring -->
        <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> 

        <!--2,配置mybatis的SqlSessionFactory,需要注入全局配置文件和连接池  -->
        <bean id="sqlSessionFactoryId" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
            <property name="dataSource" ref="dataSource"></property>
        </bean>

        <!-- 3,配置批量mapper代理开发模式,这里就不能指定id了,而是通过引用具体的mapper类名来获得mapper对象,进而操作函数 -->
        <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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值