专栏首页OSChinaMybatis和spring的整合

Mybatis和spring的整合

1 使用原始dao开发:

1.1 导入jar包:

<dependencies>
  	<dependency>
  		<groupId>org.mybatis</groupId>
  		<artifactId>mybatis</artifactId>
  		<version>3.2.7</version>
  	</dependency>
  	<dependency>
  		<groupId>commons-logging</groupId>
  		<artifactId>commons-logging</artifactId>
  		<version>1.2</version>
  	</dependency>
  	<dependency>
  		<groupId>junit</groupId>
  		<artifactId>junit</artifactId>
  		<version>4.12</version>
  	</dependency>
  	<dependency>
  		<groupId>mysql</groupId>
  		<artifactId>mysql-connector-java</artifactId>
  		<version>5.1.43</version>
  	</dependency>
  	<dependency>  
            <groupId>log4j</groupId>  
            <artifactId>log4j</artifactId>  
            <version>1.2.17</version>  
      </dependency> 
      <!-- 引入dbcp连接池 -->
      <dependency>
	    <groupId>commons-dbcp</groupId>
	    <artifactId>commons-dbcp</artifactId>
		    
	    <version>1.2.2</version>
	  </dependency>
      <dependency>
      	<groupId>cglib</groupId>
      	<artifactId>cglib</artifactId>
      	<version>3.1</version>
      </dependency>
      <dependency>
      	<groupId>org.apache.logging.log4j</groupId>
      	<artifactId>log4j-api</artifactId>
      	<version>2.8</version>
      </dependency>
      <dependency>
      	<groupId>org.apache.logging.log4j</groupId>
      	<artifactId>log4j-core</artifactId>
      	<version>2.8</version>
      </dependency>
      <dependency>
      	<groupId>org.slf4j</groupId>
      	<artifactId>slf4j-log4j12</artifactId>
      	<version>1.7.7</version>
      </dependency>
      <dependency>
      	<groupId>asm</groupId>
      	<artifactId>asm</artifactId>
      	<version>3.3</version>
      </dependency>
      <dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-ehcache</artifactId>
		    <version>1.0.0</version>
		</dependency>
		
		<!-- 加入ehcache缓存包 -->
		<dependency>
		    <groupId>org.ehcache</groupId>
		    <artifactId>ehcache</artifactId>
		    <version>3.4.0</version>
		</dependency>
		<!-- mybatis与ehcache真核包 -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-ehcache</artifactId>
		    <version>1.0.0</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.3.8.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>4.3.8.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.8.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.9</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>4.3.8.RELEASE</version>
		</dependency>
  </dependencies>

1.2 加入必要的配置文件如下(和工程目录结构)

1.3 创建pojo类 ,dao接口(如上图),

1.4 创建UserMapper.xml文件 (在sqlMap文件夹中)

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

<!-- 用原始dao开发  namespace可以随意配置 -->
<mapper namespace="test">

	<select id="selectUserById" parameterType="Integer" resultType="User">
		select * from User WHERE id=#{id}
	</select>
	
</mapper>

1.5 配置mybatis的配置文件(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> 
	<typeAliases>
		<package name="com.shi.pojo"/>
	</typeAliases>
	
	<mappers>
		<mapper resource="sqlMap/UserMapper.xml"/>
	</mappers>
</configuration>

1.6 配置spring的配置文件 (applicationContext.xml)

<?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:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee" 
	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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
	<!-- 1  加载资源文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	
	<!-- 2  配置数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}"></property>
		<property name="url" value="${jdbc.url}"></property>
		<property name="username" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="maxActive" value="10"></property>
		<property name="maxIdle" value="5"></property>
	</bean>
	
	
	<!-- 3 配置sqlSessionFactory会话工厂(在整合包中) -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 3.1 加载mybatis的配置文件 -->
		<property name="configLocation" value="mybatis/sqlMapConfig.xml"></property>
		<!-- 3.2 加载数据源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!-- 4 用原始dao开发时需要配置 dao bean -->
	<bean id="userDao" class="com.shi.dao.UserDaoImp">
		<!-- 因为继承了sqlSessionDaoSupport类 所以要把sqlSessionFactory注入进去 -->
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>
</beans>

1.7 配置 UserDaoImp的实现类

package com.shi.dao;

import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.shi.pojo.User;

/**
 * 这里继承SqlSessionDaoSupport 可以为我们自动生成sqlSession
 * @author SHF
 *
 */
public class UserDaoImp extends SqlSessionDaoSupport implements UserDao {

	public User selectUserById(Integer id) throws Exception {
		SqlSession sqlSession=this.getSqlSession();//从继承中获取会话 
		User user=sqlSession.selectOne("test.selectUserById", id);
		return user;
	}
}

1.8 编写测试类

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

import com.shi.dao.UserDao;
import com.shi.pojo.User;

public class UserDaoTest {
	
	private ApplicationContext applicationContext;
	@Before
	public void setUp() throws Exception {
		applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
	}

	@Test
	public void test() throws Exception {
		UserDao userDao=(UserDao) applicationContext.getBean("userDao");
		User user=userDao.selectUserById(1);
		System.out.println(user);
	}

}

2 使用mapper代理的开发方式(重点,完全代理)

2.1.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">

<!--namespace:必须是和mapper.java的相对路径  -->
<mapper namespace="com.shi.mapper.UserMapper">
	<!-- 开启本namespace的二级缓存 -->
	<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>

	<select id="selectUserById" parameterType="Integer" resultType="User">
		select * from User WHERE id=#{id}
	</select>
</mapper>

2.2.mapper.java 接口

package com.shi.mapper;

import java.util.List;

import com.shi.pojo.User;

public interface UserMapper {
	
	/**
	 * 操作user的mapper的接口
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public User selectUserById(Integer id)throws Exception;
}

2.3 applicationContext-dao.xml文件

<?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:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee" 
	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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
	<!-- 1  加载资源文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	
	<!-- 2  配置数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}"></property>
		<property name="url" value="${jdbc.url}"></property>
		<property name="username" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="maxActive" value="10"></property>
		<property name="maxIdle" value="5"></property>
	</bean>
	
	
	<!-- 3 配置sqlSessionFactory会话工厂(在整合包中) -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 3.1 加载mybatis的配置文件 -->
		<property name="configLocation" value="mybatis/sqlMapConfig.xml"></property>
		<!-- 3.2 加载数据源 -->
		<property name="dataSource" ref="dataSource"></property>
		
		**<!-- 如果要想mapper.java和mapper.xml文件所在位置不一样 要加上这个配置 -->
		<!-- <property name="mapperLocations" value="classpath:mybatis/mappings/**/*.xml" /> -->**
	</bean>
	
	
	<!-- 5  使用mapper代理的开发方法 (自动扫描该包下的所有接口自动生成其实现类)
		**要求**:mapper.java和mapper.xml文件必须在同一个包下面,并且名字一致
		扫描出来的mapper的bean的名字 是 mapper类名的首字符小写
	 -->
	<bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- basePackage:指定扫描的包名。 -->
		<property name="basePackage" value="com.shi.mapper"></property>
		<!-- **sqlSessionFactoryBeanName **一定要配置成这个   
			如果配置成sqlSessionFactory 那么上面的加载资源文件将 不执行(或后执行) -->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>
	
</beans>

2.4测试方法同上

3 问题:

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Hystrix-dashboard 豪猪

    用户5927264
  • spring-boot 与热部署

    用户5927264
  • mybatis使用mapper代理开发和注意点

    用户5927264
  • 第三十五章:SpringBoot与单元测试的小秘密

    恒宇少年
  • Zabbix 监控图表中文乱码的解决办法

    版权声明:本文为耕耘实录原创文章,各大自媒体平台同步更新。欢迎转载,转载请注明出处,谢谢

    耕耘实录
  • mysql用sql语句创建表和数据库设置字符编码

    set character_set_client = gbk; -- 来自客户端的语句的字符集。服务器使用character_set_client变量作为客户端...

    Sindsun
  • 智能硬件-WIFI模块测试

    客户端:我们在客户端安装所测机器上安装Performance Endpoint,查看客户端IP。

    用户6367961
  • POJ 2752 Seek the Name, Seek the Fame(KMP求公共前后缀)

    题意是给了一个字符串,求出前i位的前缀刚好是后i位的后缀,输出这些位置,比如abcab当i为2的时候前缀为ab后缀也为ab

    Ch_Zaqdt
  • SpringCloudGateway笔记(6)-请求体不全

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

    yingzi_code
  • 【LeetCode 136】 关关的刷题日记33 Intersection of Two

    关关的刷题日记33 – Leetcode 349. Intersection of Two Arrays 题目 Given two arrays, write ...

    WZEARW

扫码关注云+社区

领取腾讯云代金券