mybatis 学习笔记(四):mybatis 和 spring 的整合

尝试一下整合 mybatis 和 spring。

思路

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

整合环境

在这里我们还是使用 maven 工程来导入 jar 包。

需要用到的 jar 包:

  • spring 核心包和 spring 扩展包如 tx 和 jdbc 等 jar 包
  • mybatis 核心包
  • mybatis 和 spring 整合包
  • java 连接 MySQL 包

实例

在这里我们通过原始 dao 开发和,mapper 代理开发 dao 层两种方式来举例 mybatis 和 spring 整合的操作。

举个栗子:查询数据表中 id 为1的字段。

1

首先通过 maven 导入必要的 jar 包,pom.xml 配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>cn.itcast</groupId>
<artifactId>spring-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build> <dependencies>
<!-- 测试文件 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency> <!-- spring 框架的 jar 包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.2.4.RELEASE</version>
</dependency> <!-- spring 拓展包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.2.4.RELEASE</version>
</dependency> <!-- mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<!-- mybatis 核心jar包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- mybatis 附加功能包,如日志功能等 -->
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-launcher</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>5.2</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.5</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.22.0-GA</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.1.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency> <!-- mybatis 和 spring 整合包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency> <!-- c3po 连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>mchange-commons-java</artifactId>
<version>0.2.15</version>
</dependency> </dependencies>
</project>

2

然后我们在 resources 下建立 spring 配置文件,mybatis 全局配置文件和映射文件,封装数据库对象,完成后文件目录如图所示:

3

在 application.xml 中配置 sqlSessionFactory 和数据源:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 加载配置文件 -->
<context:property-placeholder location="classpath:config/db.properties" /> <!-- 数据源,使用c3p0 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!-- 注入属性值 -->
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean> <!-- sqlSessionFactory -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载 mybatis 的配置文件 -->
<property name="configLocation" value="config/mybatis/SqlMapConfig.xml" />
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>

5

原始的 dao 开发(和 spring整合后)。

  • 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"> <mapper namespace="test">
<select id="findUserById" parameterType="int" resultType="cn.itcast.ssm.po.User">
SELECT * FROM USER WHERE id=#{value}
</select>
</mapper>
  • 在 SqlMapconfig.xml 中加载 User.xml
    <!-- 加载映射文件 -->
<mappers>
<mapper resource="config/sqlmap/User.xml"/>
</mappers>
  • 编写接口 UserDao.java:
package cn.itcast.ssm.dao;

import cn.itcast.ssm.po.User ;

public interface UserDao {
//根据 id 查询用户信息
public User findUserById(int id) throws Exception;
}
  • 编写接口实现类 UserDaoImpl.java, 继承 SqlSessionDaoSupport 类:
package cn.itcast.ssm.dao;

import cn.itcast.ssm.po.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport; public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{ @Override
public User findUserById(int id) throws Exception {
//继承SqlSessionDaoSupport,通过this.getSqlSession()得到sqlSessoin
SqlSession sqlSession = this.getSqlSession();
User user = sqlSession.selectOne("test.findUserById",id); return user;
}
}
  • 在 applicationContext.xml 中配置 dao:
<!-- 原始 dao 接口 -->
<bean id="userDao" class="cn.itcast.ssm.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
</bean>
  • 编写测试类 testFindUserById.java ,进行测试:
package cn.itcast.ssm.dao;

import cn.itcast.ssm.po.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.InputStream; public class UserDaoImplTest { private ApplicationContext applicationContext; //在 setUp这个方法得到 spring 容器
@Before
public void setUp() throws Exception{
applicationContext = new ClassPathXmlApplicationContext("classpath:config/spring/applicationContext.xml");
} @Test
public void testFindUserById() throws Exception{
//创建 UserDao 对象
UserDao userDao = (UserDao) applicationContext.getBean("userDao"); //调用 UserDao 的方法
User user = userDao.findUserById(1); System.out.println(user);
} }
  • 测试结果如下:

6

mapper 代理开发。

同样的,使用mapper 代理开发,只需我们编写接口和配置文件,而不需要关心具体的实现类(mapper 自动生成)。

  • 编写对象接口 UserMapper.java:
package cn.itcast.ssm.mapper;

import cn.itcast.ssm.po.User;

public interface UserMapper {
//根据 id 查询用户信息
User findUserById(int id) throws Exception;
}
  • 编写 SQL 语句配置文件 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="cn.itcast.ssm.mapper.UserMapper">
<select id="findUserById" parameterType="int" resultType="user">
SELECT * FROM USER WHERE ID=#{VALUE }
</select>
</mapper>
  • 通过 MapperFactoryBean 创建代理对象:
 <!-- mapper配置
MapperFactoryBean: 根据 mapper 接口生成代理对象
-->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- mapperInterface指定mapper接口 -->
<property name="mapperInterface" value="cn.itcast.ssm.mapper.UserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
</bean>

在此方法中,我们需要针对每个 mapper 进行配置,较为麻烦。

  • 建议通过使用 MapperScannerConfigurer 进行 mapper 扫描:
    <!-- mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册
遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中
自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描的包名
如果扫描多个包,每个包中间使用半角逗号分隔
-->
<property name="basePackage" value="cn.itcast.ssm.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>
</bean>
  • 编写测试程序,查看执行结果:
package cn.itcast.ssm.mapper;

import cn.itcast.ssm.po.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class UserMapperTest {
private ApplicationContext applicationContext; //在 setUp这个方法得到 spring 容器
@Before
public void setUp() throws Exception{
applicationContext = new ClassPathXmlApplicationContext("classpath:config/spring/applicationContext.xml");
} @Test
public void testFindUserById() throws Exception{
UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper"); //调用 usrMapper 的方法
User user = userMapper.findUserById(1); System.out.println(user);
}
}

执行结果如下:

mybatis 学习笔记(四):mybatis 和 spring 的整合的更多相关文章

  1. mybatis学习笔记(四)-- 为实体类定义别名两种方法(基于xml映射)

    下面示例在mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现 Demo的基础上进行优化 以新增一个用户为例子,原UserMapper.xml配置如下: < ...

  2. Mybatis学习笔记(一) —— mybatis介绍

    一.Mybatis介绍 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名 ...

  3. MyBatis学习笔记一:MyBatis最简单的环境搭建

    MyBatis的最简单环境的搭建,使用xml配置,用来理解后面的复杂配置做基础 1.环境目录树(导入mybatis-3.4.1.jar包即可,这里是为后面的环境最准备使用了web项目,如果只是做 my ...

  4. 【Hibernate学习笔记-3】在Spring下整合Hibernate时, 关于sessionFactory的类型的说明

    摘要 在Spring下整合Hibernate时,关于sessionFactory的配置方式主要有两种,分别为注解配置方式,和xml配置方式,下面将对这两种配置方式进行介绍. 1. sessionFac ...

  5. Mybatis学习笔记(八) —— Mybatis整合spring

    一.整合思路 1.SqlSessionFactory对象应该放到spring容器中作为单例存在. 2.传统dao的开发方式中,应该从spring容器中获得sqlsession对象. 3.Mapper代 ...

  6. mybatis学习笔记四(动态sql)

    直接贴图,注解在代码上,其他的配置文件在学习一中就不贴了 1 数据库 2 实体类 package com.home.entity; /** * 此类是: 用户实体类 * @author hpc * @ ...

  7. MyBatis学习笔记(四)——解决字段名与实体类属性名不相同的冲突

    转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4264425.html 在平时的开发中,我们表中的字段名和表对应实体类的属性名称不一定都是完全相同的,下面来演 ...

  8. Mybatis学习笔记(四) —— SqlMapConfig.xml配置文件

    一.properties(属性) SqlMapConfig.xml可以引用java属性文件中的配置信息 在config下定义db.properties文件,如下所示: db.properties配置文 ...

  9. mybatis学习笔记(四)

    resultType 语句返回值类型的完整类名或别名 resultType 返回的是一个map集合,key是列名,value是对应的值 使用resultMap实现联表查询 resultMap 查询的结 ...

  10. MyBatis学习笔记(四) 注解

        使用MyBatis注解开发,可以省去类配置文件,简洁方便.但是比较复杂的SQL和动态SQL还是建议书写类配置文件. 注解还是不推荐使用的.只是了解了解!简单的CRUD可以使用注解.简单写写. ...

随机推荐

  1. 密码生成工具Cupp

    Cupp可根据已知信息生成相应的字典,用来爆破很有帮助 首先先安装一下cupp 命令:apt-get install cupp 参数说明: -v查看cupp版本号 -h 查看参数列表 -l 从gith ...

  2. java-虚拟机-索引

    底层 JVM之堆内存(年经代,老年代) Java内存泄露的理解与解决 内存溢出和内存泄漏的区别.产生原因以及解决方案 JVM内容梳理 Jvm的体系结构

  3. 【原创】基于UDP广播的局域网Web Window Service日志跟踪小工具

           一直感觉Web开发或者windows服务的日志跟踪调试不是很方便          特别是在生产环境服务器上面          目前一般的解决方案是通过各种日志工具把错误信息和调试信息 ...

  4. git配置和使用

    1.注册bitbucket用户登录bitbucket站点https://bitbucket.org/注册一个用户,注册后用户名为linjiqin,邮箱为linjiqin@dkhs.com. 2.Cre ...

  5. spring中aop原理

  6. 性能监控工具YourKit

    1.下载YourKit(在不同系统或终端下请保持版本一致) http://www.yourkit.com/java/profiler/index.jsp 2. 解压Linux的YourKit tar ...

  7. python3 破解 geetest(极验)的滑块验证码

    Kernel_wu 快速学习的实践者 python3 破解 geetest(极验)的滑块验证码 from selenium import webdriver from selenium.webdriv ...

  8. 图论算法》关于SPFA和Dijkstra算法的两三事

    本来我是想把这两个算法分开写描述的,但是SPFA其实就是Dijkstra的稀疏图优化,所以其实代码差不多,所以就放在一起写了. 因为SPFA是Dijkstra的优化,所以我想来讲讲Dijkstra. ...

  9. blockchain notes

    1. IBM blockchain platform https://www.ibm.com/blockchain/platform/ 2. 开源项目hyperledger https://hyper ...

  10. laravel实现多对多的分析

    在实际开发中多对多的开发还是比较常见的 1.1首先由migrate来创建表(文章表) 1.2同理创建标签表 1.3这是 我会的到如下结果: 2.1在数据迁移表contents中添加几个字段 publi ...