MyBatis与Spring的整合(第十章)

目录

10.1 整合环境搭建

10.11 准备所需jar包

10.12 编写配置文件

10.2 传统DAO方式的开发

整合

10.3 Mapper接口方式的开发

10.31 基于MapperFactoryBean的整合

10.4 测试事务


10.1 整合环境搭建

10.11 准备所需jar包

<dependencies>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>
			2.0.6
			</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.3.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.0.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>
			1.4
			</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.23</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.6</version>
		</dependency>
</dependencies>

10.12 编写配置文件

1 db.properties文件

2 applicationContext.xml文件

    <util:properties id="db"
		location="classpath:db.properties"></util:properties>
	<!-- 数据库连接池,配置数据源 -->
	<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="#{db.driver}"></property>
		<property name="url" value="#{db.url}"></property>
		<property name="username" value="#{db.username}"></property>
		<property name="password" value="#{db.password}"></property>
	</bean>

	<!-- 配置MyBatis工厂(SqlSessionFactoryBean),来spring集成mybatis,不需要在mybatis的配置
文件。(在配置时需指定两个参数1数据源 2MyBatis的配置文件路径。这样Spring的IOC容器就会在初始化id
为ssfb的Bean时解析MyBatis的配置文件,并与数据源一同保存到Spring的Bean中。) -->
	<bean id="ssfb" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 注入数据源 在不需要mybatis自带的连接池,而是使用spring管理的连接池 -->
		<property name="dataSource" ref="ds"></property>
		<!-- 指定核心配置文件(映射文件)的位置 -->
		<property name="mapperLocations" value="entity/*.xml"></property>

	</bean>
	<!-- 配置MapperScannerConfigurer -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 映射器所在位置 MapperScannerConfigurer负责扫描指定包下所有mapper映射器,然后生成符合这些映射器要求的对象。 
			(就是调用了SqlSession的getMapper方法)另外,还会将这些对象添加到spring容器里面。(默认id是首字母小写之后的接口名) -->
		<property name="basePackage" value="dao"></property>
		<!-- 只扫描特定接口 -->
		<property name="annotationsClass"
			value="annotations.MyBatisRepository"></property>
	</bean>

3 SqlMapConfig.xml文件

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" 
	"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<configuration>
	<environments default="environment">
		<environment id="environment">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.cj.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/netctoss?serverTimezone=UTC" />
				<property name="username" value="root" />
				<property name="password" value="1111" />
			</dataSource>
		</environment>
	</environments>
	<!-- 指定映射文件的位置 -->
	<mappers>
		<mapper resource="entity/EmpMapper.xml"/>
	</mappers>
</configuration>

10.2 传统DAO方式的开发整合

SqlSessionTemplate:是mybatis-spring的核心类,负责管理MyBatis的SqlSession,通过调用MyBatis的SQL方法(其将保证使用的SqlSession和当前Spring的事务是相关的),并管理SqlSession的声明周期(关闭、提交、回滚)。

SqlSessionDaoSupport:抽象支持类,作为Dao的基类来使用,可通过此类的.getSqlSession()方法来获取所需的SqlSession。

开发流程:

1 编写持久层。

        11 创建映射文件。

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

<mapper namespace="dao.EmpDao">
	<!-- id:要求唯一 parameterType:参数类型,要写实体类的权限名称(包名+类名) -->
	<insert id="save" parameterType="entity.Emp">
		insert into emp (name,age)
		values(#{name},#{age});
	</insert>

	<!-- id:要求唯一 resultType:返回的数据类型 parameterType:参数的类型 -->
	<select id="findAll" resultType="entity.Emp">
		select * from emp;
	</select>

	<select id="findById" parameterType="int"
		resultType="entity.Emp">
		select * from emp where id=#{id}
	</select>

	<update id="modify" parameterType="entity.Emp">
		update emp set
		name=#{name},age=#{age} where id=#{id};
	</update>

	<delete id="delete" parameterType="int">
		delete from emp where id =
		#{id};
	</delete>

	<!-- 返回Map类型的结果 mybatis会将查询结果先封装到一个Map对象里面(以字段名为key,以字段值为value) 然后再将Map对象中的数据添加到实体对象里面 
		key:value id:1 name:json age:18 -->
	<select id="findById2" parameterType="int" resultType="map">
		select *
		from emp where id=#{id}
	</select>

	<!-- 使用ResultMap解决表的字段名与实体类的属性名不一致的情况 -->
	<select id="findById3" parameterType="int" resultMap="emp2Map">
		select *
		from emp where id = #{id}
	</select>
	
	<!-- 处理表的字段名与实体类的属性名的对应关系 -->
	<resultMap type="entity.Emp2" id="emp2Map">
		<result property="empNo" column="id" />
		<result property="ename" column="name" />
	</resultMap>

</mapper>

        12指定映射文件位置

<!-- 指定映射文件的位置 -->
<mappers>
		<mapper resource="entity/EmpMapper.xml"/>
</mappers>

2 实现Dao层

        21 创建接口并创建操作数据库方法

/*映射器*/
@Repository("eDao")
@MybatisRepository
public interface EmpDao {
public void save(Emp emp);
	
	public List<Emp> findAll();
	
	public Emp findById(int id);
	
    public void modify(Emp emp);
	
	public void delete(int id);
	
	public Map findById2(int id);
	
	public Emp2 findById3(int id);
	
}

        22 创建接口的实现类

/*SqlSessionDaoSupport类在使用时需要一个SqlSessionFactory或SqlSessionTemplate对象,
 * 所以要通过Spring给此类的子类对象注入一个SqlSessionFactory或SqlSessionTemplate对象,
 * 就能在子类中通过调用此类中的.getSqlSession()来获取SqlSession对象,并使用SqlSession对象中的方法了。*/
public class EmpDaoImpl extends SqlSessionDaoSupport implements EmpDao {
    ...
	public Emp findById(int id) {
		return this.getSqlSession().selectOne("entity" + ".EmpMapper.xml.findById", id);
	}
	...
}

        23 在配置文件中编写实例化/EmpDaoImpl的配置

<!--实例化Dao (将SqlSessionFactory对象注入到了Bean的实例化对象中)-->
<bean id="EmpDao" class="dao/impl/EmpDaoImpl.java"> 
	<property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
</bean>

3 整合测试(成功操作数据库则MyBatis和Spring整个成功)

        测试中获取Bean的两种方式:

        1 根据容器中的Bean的id来获取指定Bean的方式。

ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
EmpDao eDao=(EmpDao) ac.getBean("eDao");

        2 通过Spring容器,根据类的类型来获取Bean的实例(此种不用强转)。

ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
dao=ac.getBean("eDao",EmpDao.class);

10.3 Mapper接口方式的开发

(传统的Dao整合方式:1出现大量重复代码 2指定映射文件中的执行语句id时运行前不能确定是否正确)

开发流程:

1 创建接口及对应Sql语句映射文件,并引入映射文件。

<mappers><!-- 指定映射文件的位置 -->
		<mapper resource="entity/EmpMapper.xml" />
</mappers>

10.31 基于MapperFactoryBean的整合

10.4 测试事务

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    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/aop http://www.springframework.org/schema/aop/spring-aop-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/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
    <util:properties id="db"
        location="classpath:db.properties"></util:properties>
    <!-- 数据库连接池,配置数据源 -->
    <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="#{db.driver}"></property>
        <property name="url" value="#{db.url}"></property>
        <property name="username" value="#{db.username}"></property>
        <property name="password" value="#{db.password}"></property>
    </bean>

    <!-- 配置MyBatis工厂(SqlSessionFactoryBean),来spring集成mybatis,不需要在mybatis的配置 
        文件。(在配置时需指定两个参数1数据源 2MyBatis的配置文件路径。这样Spring的IOC容器就会在初始化id 为ssfb的Bean时解析MyBatis的配置文件,并与数据源一同保存到Spring的Bean中。) -->
    <bean id="ssfb" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 在不需要mybatis自带的连接池,而是使用spring管理的连接池 -->
        <property name="dataSource" ref="ds"></property>
        <!-- 指定核心配置文件(映射文件)的位置 -->
        <property name="mapperLocations" value="entity/*.xml"></property>

    </bean>
    <!-- 配置MapperScannerConfigurer -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 映射器所在位置 MapperScannerConfigurer负责扫描指定包下所有mapper映射器,然后生成符合这些映射器要求的对象。 
            (就是调用了SqlSession的getMapper方法)另外,还会将这些对象添加到spring容器里面。(默认id是首字母小写之后的接口名) -->
        <property name="basePackage" value="dao"></property>
        <!-- 只扫描特定接口 -->
        <property name="annotationsClass"
            value="annotations.MyBatisRepository"></property>
    </bean>
    <!-- 传统Dao方式的整合开发
    实例化Dao (将SqlSessionFactory对象注入到了Bean的实例化对象中)
     <bean id="EmpDao" class="dao/impl/EmpDaoImpl.java"> 
        <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
    </bean> -->
</beans>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值