Spring与MyBatis的集成

前言

前面已经学习了Spring以及MyBatis的相关知识,那么这一章就说一下Spring与MyBatis的集成。有两种方式。

一、方式一 使用MapperScannerConfigurer

1.1 新建项目并导包

新建一个maven项目,并导入如下jar包。

<dependencies>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-webmvc</artifactId>
  		<version>5.1.2.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.mybatis</groupId>
  		<artifactId>mybatis</artifactId>
  		<version>3.4.5</version>
  	</dependency>
  	<dependency>
  		<groupId>org.mybatis</groupId>
  		<artifactId>mybatis-spring</artifactId>
  		<version>1.3.1</version>
  	</dependency>
  	<dependency>
  		<groupId>com.oracle</groupId>
  		<artifactId>ojdbc14</artifactId>
  		<version>10.2.0.5.0</version>
  	</dependency>
  	<dependency>
  		<groupId>commons-dbcp</groupId>
  		<artifactId>commons-dbcp</artifactId>
  		<version>1.4</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-jdbc</artifactId>
  		<version>5.1.2.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>junit</groupId>
  		<artifactId>junit</artifactId>
  		<version>4.12</version>
  	</dependency>
  </dependencies>

1.2 创建spring配置文件

这里将mybatis的配置也写在了spring中。
通过配置SqlSessionFactoryBean可以得到连接池和mapper映射文件。
配置MapperScannerConfigurer,该bean负责调用sqlsession的getMapper方法,创建符合mapper映射器要求的对象,并将对象添加到spring容器中,所以这个测试项目的配置中未曾配置组件扫描,但是仍然可以将对象添加到容器中。

<?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:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd     
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
	
    <!-- 获取数据库连接配置 -->
 	<util:properties id="dbConfig" location="classpath:db.properties"></util:properties>

 	<!-- 连接池 -->
 	<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
 	    <property name="driverClassName" value="#{dbConfig.driver}"></property>
 	    <property name="url" value="#{dbConfig.url}"></property>
 	    <property name="username" value="#{dbConfig.username}"></property>
 	    <property name="password" value="#{dbConfig.password}"></property>
 	</bean>
 	
 	<!-- mybatis的配置,包括连接池和映射文件地址 -->
 	<bean id="ssfb" class="org.mybatis.spring.SqlSessionFactoryBean">
 	    <property name="dataSource" ref="ds"></property>
 	    <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
 	</bean>
 	
 	<!-- 生成符合映射器的对象  相当于SqlSession.getMapper() -->
 	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
 	    <property name="basePackage" value="dao"></property>
 	</bean>
</beans>

1.3 实体类

因为dao这种有两个实体类,这里就一并列出,也是因为懒不想改动以前的代码~~这里的基础类都是上一章用到的,感兴趣的可以去看一下上一章MyBatis框架

package entity;

public class Dept {
	private String deptno;
	private String deptname;
	private String num;
	public String getDeptno() {
		return deptno;
	}
	public String getDeptname() {
		return deptname;
	}
	public String getNum() {
		return num;
	}
	public void setDeptno(String deptno) {
		this.deptno = deptno;
	}
	public void setDeptname(String deptname) {
		this.deptname = deptname;
	}
	public void setNum(String num) {
		this.num = num;
	}
	@Override
	public String toString() {
		return "Dept [deptno=" + deptno + ", deptname=" + deptname + ", num=" + num + "]";
	}
}
package entity;

public class Dept2 {
	private String id;
	private String name;
	private String num;
	public String getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public String getNum() {
		return num;
	}
	public void setId(String id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setNum(String num) {
		this.num = num;
	}
	@Override
	public String toString() {
		return "Dept2 [id=" + id + ", name=" + name + ", num=" + num + "]";
	}
}

1.4 Dao

也可以成为映射器。这是一个接口文件。

package dao;

import java.util.List;
import java.util.Map;

import entity.Dept;
import entity.Dept2;

public interface DeptDao {
	public void insertOne(Dept dept);
	public void deleteOne(String id);
	public void updateOne(Dept dept);
	public List<Dept> findAll();
	public Dept findById(String id);
	public Dept2 findById2(String id);
	public Dept2 findById3(String id);
	public Map findById4(String id);
}

1.5 mapper映射文件

<?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="dao.DeptDao">
    <insert id="insertOne" parameterType="entity.Dept">
        insert into dept(deptno,deptname,num)values(#{deptno},#{deptname},#{num})
    </insert>
    <delete id="deleteOne" parameterType="String">
        delete from dept where deptno=#{deptno}
    </delete>
    <update id="updateOne" parameterType="entity.Dept">
        update dept set deptname=#{deptname},num=#{num} where deptno=#{deptno}
    </update>
    <select id="findById" resultType="entity.Dept">
        select * from dept where deptno=#{deptno}
    </select>
    <select id="findAll" resultType="entity.Dept">
        select * from dept
    </select>
    
    <select id="findById2" resultType="entity.Dept2">
        select deptno id,deptname name,num from dept where deptno=#{deptno}
    </select>
    
    <select id="findById3" resultMap="deptmap">
        select * from dept where deptno=#{deptno}
    </select>
    
    <resultMap type="entity.Dept2" id="deptmap">
        <result property="id" column="deptno" />
        <result property="name" column="deptname" />
    </resultMap>
    
    
    <select id="findById4" resultType="map">
        select * from dept where deptno=#{deptno}
    </select>
    
</mapper>

1.6 测试

此处测试只测试了一个方法,作为示例,感兴趣的小伙伴可以将其他的方法做一个测试,前面的代码以及有了,就只是增加测试方法。

package test;

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

import dao.DeptDao;

public class Test {
	private DeptDao dao;
	@Before
	public void initInfo(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
		dao = ac.getBean("deptDao",DeptDao.class);
	}
	
	@org.junit.Test
	public void test1(){
		System.out.println(dao.findAll());
	}
}

二、方式二 使用SqlSessionTemplate

这种方式很类似JdbcTemplate,都是将sql封装成模板对象,直接调用相应的方法即可。

2.1 配置文件

配置SqlSessionTemplate和组件扫描,此时不再需要配置上面的MapperScannerConfigurer。

<?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:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd     
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
	
    <!-- 获取数据库连接配置 -->
 	<util:properties id="dbConfig" location="classpath:db.properties"></util:properties>

 	<!-- 连接池 -->
 	<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
 	    <property name="driverClassName" value="#{dbConfig.driver}"></property>
 	    <property name="url" value="#{dbConfig.url}"></property>
 	    <property name="username" value="#{dbConfig.username}"></property>
 	    <property name="password" value="#{dbConfig.password}"></property>
 	</bean>
 	
 	<!-- mybatis的配置,包括连接池和映射文件地址 -->
 	<bean id="ssfb" class="org.mybatis.spring.SqlSessionFactoryBean">
 	    <property name="dataSource" ref="ds"></property>
 	    <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
 	</bean>
 	
 	<!-- 生成符合映射器的对象  相当于SqlSession.getMapper() -->
 	<!-- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
 	    <property name="basePackage" value="dao"></property>
 	</bean> -->
 	
 	<!-- 将SqlSessionFactory通过构造器方式注入 -->
 	<bean id="sst" class="org.mybatis.spring.SqlSessionTemplate">
 	    <constructor-arg index="0" ref="ssfb"></constructor-arg>
 	</bean>
 	
 	<!-- 组件扫描 -->
 	<context:component-scan base-package="dao" />
 	
</beans>

2.2 映射器的实现类

需要编写一个映射器也就是dao的实现类,该类中注入SqlSessionTemplate,方法中调用其中的方法即可,此处以findAll作为示例,其他的方法未写全。

package dao;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

import entity.Dept;
import entity.Dept2;

@Repository("deptDaoImpl")
public class DeptDaoImpl implements DeptDao {
	
	@Resource(name="sst")
	private SqlSessionTemplate sst;

	public void insertOne(Dept dept) {
		// TODO Auto-generated method stub

	}

	public void deleteOne(String id) {
		// TODO Auto-generated method stub

	}

	public void updateOne(Dept dept) {
		// TODO Auto-generated method stub

	}

	public List<Dept> findAll() {
		List<Dept> list = sst.selectList("dao.DeptDao.findAll", Dept.class);
		return list;
	}

	public Dept findById(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	public Dept2 findById2(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	public Dept2 findById3(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	public Map findById4(String id) {
		// TODO Auto-generated method stub
		return null;
	}
}

2.3 测试

其他的类都是和上面一致的,无需改动。
测试方法有所变化,如下:

package test;

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

import dao.DeptDao;

public class Test {
	private DeptDao dao;
	@Before
	public void initInfo(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
		dao = ac.getBean("deptDaoImpl",DeptDao.class);
	}
	
	@org.junit.Test
	public void test1(){
		System.out.println(dao.findAll());
	}
}

此时获取的bean是deptDaoImpl,也就是实现类的bean。

至此,Spring与MyBatis的集成就说完了,两种方式相比,第一种方式较为常用一点。第二种方式略微复杂一些。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值