您的位置:首页 > 编程语言 > Java开发

[置顶] 【Mybatis】深入浅出Mybatis(十一)——Mybatis和Spring整合

2017-03-12 15:39 561 查看

一、前言

前一篇博客中向大家介绍了Mybatis的逆向工程,根据数据库生成我们所需要的映射文件和实体文件以及操作接口。这个过程是很刺激的,从此以后只要我们拥有了数据库就可以直接生成自己的持久层了。

我们都知道Mybatis是不是自己使用的,一般都托管于Spring。所以这篇博客,小编向大家介绍mybatis与Spring的整合。

二、整合过程

2.1整合思路

1. 创建新的java Project

2. 导入整合所需要的jar包(包括mybatis、spring、整合jar、数据库连接等),下载点击这里

3. 建立配置文件,包括spring和mybatis的核心配置文件,log4j日志文件。

4. 把逆向工程生成的类和映射文件拷贝进来。为了方便测试,小编就只拷贝了User的相关文件。

5.测试

2.2 建立新的java Project

这一步很简单,New——>Java Project,输入项目名称,小编命名为SM。建立完成后,添加一个名字为lib的文件夹,用于存放相应的jar包。



2.3 导入整合所需要的jar包

把所有的jar包拷贝到lib文件夹中。



然后我们把这些jar包,add to build path, 关于关于jar包add to build path与放入lib下的区别,请跳转

2.4 建立配置文件

我们要建立的文件包括:

spring核心配置文件:applicationContext.xml

mybatis核心配置文件:SqlMapConfig.xml

数据库连接池配置文件:db.properties

log4j日志配置文件:log4j.properties

其中比较固定的有,log4j文件:

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n


db.properties文件,您只需修改自己数据库对应的字段:

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username = root
jdbc.password=123456


spring配置文件中可以加载数据库配置文件,所以将数据库连接池托付给spring管理。通过context:property-placeholder标签。

spring通过单例的方式管理SqlSessionFactory。spring和Mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession。当创建sqlsession的时候需要传入mybatis的配置文件,所以要在其中加载mybatis的全局配置文件。



applicationContext文件(未添加mapper映射):

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />

<!-- 数据源,使用dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>

<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:SqlMapConfig.xml" />
</bean>

<!-- 后面加载映射 -- >
</beans>


由于咱们添加了spring,mybatis的配置文件也有改变这个里面的内容也得根据在spring中的映射方式来修改mybatis的配置文件。mybatis的配置文件具体的操作看下文测试。

下面给出一个SqlMapConfig.xml的原始框架,这里要注意的是前面的xml文件的头文件:

<?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>

<mappers>

</mappers>

</configuration>


3.5 加入逆向工程生成的类和映射文件



三、整合测试

这里使用的是mapper代理方法的测试。

3.1 建立测试类和方法

建立新的包,小编命名为“cn.itcast.ssm.test”,在这个包内建立一个测试类“TestUser.java”,写下面的代码:

package cn.itcast.ssm.test;

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

import cn.itcast.ssm.mapper.UserMapper;
import cn.itcast.ssm.po.User;
/**
* 测试类
* @author Ares
* 2017年3月12日11:30:34
*/
public class TestUser {
ApplicationContext applicationContext;
/**
* 类加载的时候首先加载这个方法,用于创建一个ApplicationContext
*/
@Before
public void setUp(){
applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

}

/**
* 测试User的查询主键方法
* @throws Exception
*/
@Test
public void testselectByPrimaryKey() throws Exception{
UserMapper userMapper = (UserMapper)applicationContext.getBean("userMapper");

//调用userDao方法
User user = userMapper.selectByPrimaryKey(1);
System.out.println(user.getUsername());
}
}


3.2 Spring配置文件和mybatis配置文件

下面是比较重要的地方了,要在Spring配置文件和mybatis中配置。这里要分情况了:

方法一 通过MapperScannerConfigurer进行mapper扫描(建议使用)

只需要配置spring就可以了,不用配置mybatis的SqlMapConfig.xml文件。mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册。

规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中,自动扫描出来的mapper的bean的id为mapper类名(手写字母小写)。

比如在测试方法中写的(UserMapper)applicationContext.getBean(“userMapper”);这里用到的就是userMapper,如果我们要查询items表的,就写成(UserMapper)applicationContext.getBean(“itemsMapper”);

在spring的applicationContext.xml配置文件中添加下面的代码:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描的包名
如果扫描多个包,每个包中间使用半角逗号分隔 -->
<property name="basePackage" value="cn.itcast.ssm.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>


方法二 8.5.2 通过MapperFactoryBean创建代理对象

此方法问题:

需要在spring中的每一个mapper进行配置,麻烦。而且要在mybatis的SqlMapConfig.xml配置文件中配置。

举例:如果我现在有两个需求:

1. 根据用户的id查询用户信息

2.根据items的id查询items信息

这样的话,就需要在Spring中配置两次,因为涉及到了两张表:

applicationContext.xml文件中添加:

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- mapperInterface指定mapper接口 -->
<property name="mapperInterface" value="cn.itcast.ssm.mapper.UserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

<bean id="itemsMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- mapperInterface指定mapper接口 -->
<property name="mapperInterface" value="cn.itcast.ssm.mapper.ItemsMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>


SqlMapConfig.xml文件更新为:

<?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>

<mappers>
<!-- 批量映射 -->
<!-- mapper会自动查询这个包下的所有的映射文件 -->
<package name="cn.itcast.ssm.mapper"/>
</mappers>

</configuration>


测试方法:

package cn.itcast.ssm.test;

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

import cn.itcast.ssm.mapper.ItemsMapper;
import cn.itcast.ssm.mapper.UserMapper;
import cn.itcast.ssm.po.Items;
import cn.itcast.ssm.po.User;
/**
* 测试类
* @author Ares
* 2017年3月12日11:30:34
*/
public class TestUser {
ApplicationContext applicationContext;
/**
* 类加载的时候首先加载这个方法,用于创建一个ApplicationContext
*/
@Before
public void setUp(){
applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

}

/**
* 测试User的查询主键方法
* @throws Exception
*/
@Test
public void testUserselectByPrimaryKey() throws Exception{
UserMapper userMapper = (UserMapper)applicationContext.getBean("userMapper");

//调用userDao方法
User user = userMapper.selectByPrimaryKey(1);
System.out.println(user.getUsername());
}

/**
* 测试Item的查询主键方法
* @throws Exception
*/
@Test
public void testItemsselectByPrimaryKey() throws Exception{
ItemsMapper itemsMapper = (ItemsMapper)applicationContext.getBean("itemsMapper");

//调用userDao方法
Items items = itemsMapper.selectByPrimaryKey(1);
System.out.println(items.getName());
}
}


testUserselectByPrimaryKey测试结果:



testItemsselectByPrimaryKey测试结果:



四、遇到的问题

4.1 问题:Document root element “mapper”, must match DOCTYPE root “configuration”.



原因是自己写的mapper.xml的开头的约定不一样,复制的时候没有留意,直接就使用了。

举例:

错误的UserMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<mapper namespace="cn.itcast.ssm.mapper.UserMapper">

<select id="findUserByIdMapper" parameterType="int"
resultType="cn.itcast.ssm.po.User">
SELECT * from user where id =#{value}
</select>

</mapper>


正确的UserMapper.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="findUserByIdMapper" parameterType="int"
resultType="cn.itcast.ssm.po.User">
SELECT * from user where id =#{value}
</select>

</mapper>


4.2 控制台报 Invoking destroy method ‘close’ on bean with name ‘dataSource’

这个显然是路径的错误,在xml文件中引用其他的文件的时候,路径出了错误。这里小编总结几个知识点:From 官网



五、小结

通过这次的学习,终于把mybatis和spring进行了结合,这个真的是没有问题的了,而且开发也是非常的迅速,系统非常的灵活,越来越的感受到这个东西的好处了。

到这里为止小编的Mybatis是基本就接近尾声了,以后会向大家推荐更好的文章。另外也希望大家多多支持。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: