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

来源:互联网 发布:深圳cnc编程学徒招聘 编辑:程序博客网 时间:2024/06/08 05:35

前言

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 configurationPUBLIC "-//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 mapperPUBLIC "-//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。

1 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 长痘留下的红印怎么办 熬夜长出的痘痘怎么办 脸上两边长痘痘怎么办 我左脸比右脸大怎么办 左脸莫名肿了怎么办 牙疼得半边脸痛怎么办 手和脸突然发麻怎么办 右半边脸麻木了怎么办 左边脸突然肿了怎么办 左半边脸皮肤疼怎么办 脸内侧的肉肿了怎么办 上火引起的脸肿怎么办 脸肿里面有硬块怎么办 内分泌失调引起的肥胖怎么办 宝宝接种证丢了怎么办 不给补办接种证怎么办 儿童接种证丢了怎么办 疫苗接种本丢了怎么办 脊灰滴剂滴多了怎么办 鞋小了挤脚趾头怎么办 大母脚趾头疼是怎么办 小脚趾内侧长茧怎么办 小脚趾肿了很痛怎么办 穿袜子大脚趾痛怎么办 脚指头长水泡很痒怎么办 走路脚打起泡了怎么办 剪完脚趾甲肿了怎么办 大脚趾关节处疼怎么办 战士10穿不进去怎么办 脚上皮肤干燥起皮怎么办 脚趾头冻了很痒怎么办 大脚趾里面有脓怎么办 大脚趾肉肿了怎么办 大脚趾边上肿了怎么办 大母脚趾关节疼怎么办 大脚趾有点歪了怎么办 大脚趾扭伤肿了怎么办 大脚趾外翻怎么办 知乎 颈椎带着胳膊疼怎么办 胳膊酸困无力是怎么办 腰疼引起的腿麻怎么办