spring(三) spring与mybatis整合

版权声明:版权所有,如需转载,请注明出处 https://blog.csdn.net/houdezaiwu1/article/details/83716063

作为Bean容器,spring框架提供了IOC机制,可以接管所有组件的创建工作,并管理,整合的主要目标就是将mybatis的核心组件方放到spring中。

具体的是mybatis的核心是获取sqlSession对象,而sqlSession对象依赖于SqlSessionFactroy实例,而SqlSessionFactroy实例依赖于SqlSessionFactoryBuilder,Spring通过读取mybatis的配置文件,构建这些组件,管理这些组件的生命周期。

一、阶段一:通过sqlSessionTemplate实现

1. 创建实体类Student

package com.pojo;

public class Student {
	private String id;
	private String name;
	private String address;
	private int age;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Student(String id, String name, String address, int age) {
		super();
		this.id = id;
		this.name = name;
		this.address = address;
		this.age = age;
	}
	public Student() {
		super();
	}
	
}

2. 创建访问接口StudentDao

package com.dao;

import java.util.List;

import com.pojo.Student;

public interface StudentDao {
	public int getCount(); //查询总数
	public List<Student> getStuList(); //返回所有信息
	public int insert(Student stu); //插入信息
}

3. 创建sql映射文件StudentMapper.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="com.dao.StudentDao">
	<resultMap type="Student" id="stuList">
		<result property="id" column="id"/>
		<result property="name" column="name"/>
		<result property="address" column="address"/>
		<result property="age" column="age"/>
	</resultMap>
	<select id="getCount" resultType="int">
		select count(1) from student
	</select>
	<select id="getStuList" resultMap="stuList">
		select * from student
	</select>
	<insert id="insert" parameterType="Student">
		insert into student values (#{id},#{name},#{address},#{age})
	</insert>
</mapper>

4. 配置mybatis-config.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mbatis-3-config.dtd">
<configuration>
	<!-- 1.设置运行时的行为,本次添加日志记录 -->
	<settings>
		<!-- 设置日志记录 -->
		<setting name="logImpl" value="LOG4J"/>
		<setting name="autoMappingBehavior" value="NONE"/>
	</settings>
	
	<!-- 2.为类定义别名 -->
	<typeAliases>
		<!-- 指定包名pojo,MyBatis会自动扫描下面的JavaBean -->
		<package name="com.pojo"/>
	</typeAliases>
	
</configuration>

可以看到,将数据源和mapper映射文件去掉了,我们一会在 spring 的 applicationContext.xml 配置这些。

5. 创建业务实现类StudentDaoImpl

package com.service;

import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import com.dao.StudentDao;
import com.pojo.Student;

public class StudentDaoImpl implements StudentDao {

	private SqlSessionTemplate sqlSession;
	
	public SqlSessionTemplate getSqlSession() {
		return sqlSession;
	}

	public void setSqlSession(SqlSessionTemplate sqlSession) {
		this.sqlSession = sqlSession;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return sqlSession.selectOne("com.dao.StudentDao.getCount"); //这种一般不用,用下边的Mapper绑定的
	}

	@Override
	public List<Student> getStuList() {
		// TODO Auto-generated method stub
		return sqlSession.getMapper(StudentDao.class).getStuList();
	}

	@Override
	public int insert(Student stu) {
		// TODO Auto-generated method stub
		return sqlSession.getMapper(StudentDao.class).insert(stu);
	}

}

sqlSesionTemplate代替了原来的SqlSession来操作数据库会话,它实现类mybatis的SqlSession接口,可以更好的配合spring进行管理。

6. 配置主要的applicationContext.xml文件,进行整合

<?xml version="1.0" encoding="UTF-8"?>
<!-- p:p命名空间;context:注解;aop:aop增强;tx:事务管理 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	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" default-autowire="byName"> 
	<!-- 1.配置数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
		<property name="username" value="xudong"></property>
		<property name="password" value="123456"></property>
	</bean> 
	<!-- 2.配置SqlSessionfactoryBean  -->
	 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>	<!--引入数据源组件  -->
		<property name="configLocation" value="classpath:mybatis-spring-config.xml"/> <!-- 加载batis核心配置文件 -->
		<property name="mapperLocations">
			<list><value>classpath:com/dao/*.xml</value></list>
		</property>
	</bean>	
	<!-- 3. 配置sqlSessionTemplate -->
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg>
			<ref bean="sqlSessionFactory"/>
		</constructor-arg>
	</bean>
	<!-- 4. 为Dao组件注入sqlSessionTemplate 实例	 -->
	<bean id="StudentDaoImpl" class="com.service.StudentDaoImpl">
		<property name="sqlSession" ref="sqlSessionTemplate"></property>
	</bean>	 
</beans>		

我们的目的就是为了获得SqlSessionTemplate实例,并装配到业务实现类中,具体步骤很简单,就是通过引入数据源和mapper映射,获得sqlSessonFactory,其中SqlSessionFactoryBean封装了SqlSessionFactoryBuilder实例化工厂的过程。然后利用工厂对象实例化SqlSessionTemplate。

为了方便可以引入外部数据源,上边的配置可以更改如下:

<?xml version="1.0" encoding="UTF-8"?>
<!-- p:p命名空间;context:注解;aop:aop增强;tx:事务管理 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	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" default-autowire="byName"> 
	<!-- 1.配置数据源 -->
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:database.properties"/>
	</bean>
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${driver}"></property>
		<property name="url" value="${url}"></property>
		<property name="username" value="${userName}"></property>
		<property name="password" value="${password}"></property>
	</bean>
	<!-- 2.配置SqlSessionfactoryBean  -->
	 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>	<!--引入数据源组件  -->
		<property name="configLocation" value="classpath:mybatis-spring-config.xml"/> <!-- 加载batis核心配置文件 -->
		<property name="mapperLocations">
			<list><value>classpath:com/dao/*.xml</value></list>
		</property>
	</bean>	
	<!-- 3. 配置sqlSessionTemplate -->
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg>
			<ref bean="sqlSessionFactory"/>
		</constructor-arg>
	</bean>
	<!-- 4. 为Dao组件注入sqlSessionTemplate 实例	 -->
	<bean id="StudentDaoImpl" class="com.service.StudentDaoImpl">
		<property name="sqlSession" ref="sqlSessionTemplate"></property>
	</bean>	 
</beans>		

同时增加数据库配置的properties文件

driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
userName=xudong
password=123456

6. 测试

	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		StudentDao stuDao=(StudentDao)ac.getBean("StudentDaoImpl");
		System.out.println("查询 getCount() 总数为: "+stuDao.getCount());
		List<Student> stuList = stuDao.getStuList();
		System.out.println(stuList);
	}

结果为:

查询 getCount() 总数为: 12
[com.pojo.Student@34f5090e, com.pojo.Student@31e5415e, com.pojo.Student@a2431d0, com.pojo.Student@1cbb87f3, com.pojo.Student@1a4013, com.pojo.Student@1b6e1eff, com.pojo.Student@306f16f3, com.pojo.Student@702b8b12, com.pojo.Student@22e357dc, com.pojo.Student@49912c99, com.pojo.Student@10163d6, com.pojo.Student@2dde1bff]
 

二、阶段二:使用MapperFactoryBean注入映射器

在上边的阶段一种,需要studentDao的实现类来操作,代码较多,可以将mapper映射器注入到StudentDao。

删除上面的StudentDaoImpl类,

然后applicatonContext.xml配置文件改造:

<?xml version="1.0" encoding="UTF-8"?>
<!-- p:p命名空间;context:注解;aop:aop增强;tx:事务管理 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	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" default-autowire="byName"> 
	<!-- 1.配置数据源 -->
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:database.properties"/>
	</bean>
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${driver}"></property>
		<property name="url" value="${url}"></property>
		<property name="username" value="${userName}"></property>
		<property name="password" value="${password}"></property>
	</bean>
	<!-- 2.配置SqlSessionfactoryBean  -->
	 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>	<!--引入数据源组件  -->
		<property name="configLocation" value="classpath:mybatis-spring-config.xml"/> <!-- 加载batis核心配置文件 -->
		<property name="mapperLocations">
			<list><value>classpath:com/dao/*.xml</value></list>
		</property>
	</bean>	
	<!-- 3. 使用MapperFactoryBean,不必每次都调用getMapper()方法,通过配置,直接为业务对象注入映射器实现
改造上面的第3和第4点 -->
	<bean id="studentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="mapperInterface" value="com.dao.StudentDao"></property>
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>
</beans>		

MapperFactoryBean直接为dao层注入sql映射的实现,不用创建实现类,减少了代码量;

mapperInterface 属性指定映射器,后边的value只能是接口类型;

本例中sql映射文件和映射器类StudentDao类路径相同,都在dao包下,不用指定sql映射文件位置,如果不一样,需要指定位置。

测试类:

public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		StudentDao stuDao=(StudentDao)ac.getBean("studentMapper");
		System.out.println("查询 getCount() 总数为: "+stuDao.getCount());
		List<Student> stuList = stuDao.getStuList();
		System.out.println(stuList);
	}

直接获取StudentDao类型的映射器。

测试结果同上!

三、阶段三:使用MapperScannerConfigurer注入映射器

上边二中,会产生大量的会产生大量的映射器配置,简单的做法是扫描指定的包,自动注册为MapperFactoryBean,省去了配置;

修改配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<!-- p:p命名空间;context:注解;aop:aop增强;tx:事务管理 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	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" default-autowire="byName"> 
	<!-- 1.配置数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
		<property name="username" value="xudong"></property>
		<property name="password" value="123456"></property>
	</bean> 
	<!-- 2.配置SqlSessionfactoryBean  -->
	 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>	<!--引入数据源组件  -->
		<property name="configLocation" value="classpath:mybatis-spring-config.xml"/> <!-- 加载batis核心配置文件 -->
		<property name="mapperLocations">
			<list><value>classpath:com/dao/*.xml</value></list>
		</property>
	</bean>	
	<!-- 3
	 使用MapperSacnnerConfigurer注入映射器,扫描指定包中的接口,直接注册为MapperFactoryBean,简化了配置
		会自动注入sqlSessionFactory实例,不必再显式注入,如果有多个factory实例,则需要注入 -->	
	<bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.dao"/> <!-- 指定扫描的基准包,包括下面的子包,可以包含多个包名,用逗号隔开 -->
		<!-- <property name="sqlSessionFactoryBeanName" ref="sqlSessionFactory"></property> -->
	</bean>
</beans>		

有个问题,就是当引用外部数据源会报错,所有直接配置了。

自动注册的映射器名称是接口名称的小写第一个字母,本例是 studentDao.

如果配有多个sqlSessionFactory,需要在配置中指定,如果一个,就不用配置,MapperScannerConfigurer会自动注入。

四、阶段四:使用注解,不用再配置文件声明bean

在配置文件中加入:

<context:component-scan base-package="cn.smbms.service"    />

几个常用的注解说明:

@Component: 比较宽泛,注解一个bean

@Repository:  标注接口

@Service: 标注业务类

@Controller: 标准控制器类

@Autiwired: 按类型匹配,可以配合 @Qualifier使用,

@Qualifier:指定@Autiwired标住的Bean的名称

@Resource: 按照名称先查找注入,如果没有就查找类型注入,如果注解在setter方法,bean的名称就是通过setter方法得到的属性名。

猜你喜欢

转载自blog.csdn.net/houdezaiwu1/article/details/83716063