Javaweb学习笔记(MyBatis和Spring的整合)

整合环境搭建

(1)Spring框架所需的包
在这里插入图片描述
(2)MyBatis框架所需的包,包括核心包和解压文件夹中lib目录中的所有lib所有JAR
(3)MyBatis与Spring整合的中间JAR
mybatis-spring-1.3.1.jar
下载地址:https://repo1.maven.org/maven2/org/mybatis/mybatis-spring/1.3.1/
在这里插入图片描述
(4)数据库驱动JAR包
在这里插入图片描述
(5)数据源所需的JAR包
在这里插入图片描述

编写配置文件

(1)创建一个zhengheWeb 项目,将上述所有包导入,在src目录下,分别创建db.properties文件。Spring的配置文件以及MyBatis的配置文件
db.proerties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5

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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        <context:property-placeholder location="classpath:db.properties"/>
        <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        	 <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="maxTotal" value="${jdbc.maxTotal}"/>
 			<property name="maxIdle"  value="${jdbc.maxIdle}"/>
 			<property name="initialSize" value="${jdbc.initialSize}"/>
        </bean>
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        	<property name="dataSource" ref="dataSource"/>
        </bean>
        <tx:annotation-driven transaction-manager="transactionManager"/>
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        	<property name="dataSource" ref="dataSource"/>
        	<property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
</beans>

在上述代码中,首先读取了properties文件的配置,然后配置了数据源,接下来开始事务管理器,并开启了事务注解,最后配置了MyBatis工厂来和Spring整合。其中MyBatis作用就是构建SqlSessionFactory,通过mybatis-spring包中提供的irg,mybatis.spring.SqlSessionFactoryBean类来配置的。
mybatis-config.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.itheima.po"/>
	</typeAliases>
	<mappers>
	
	</mappers>
</configuration>

传统DAO方式的开发整合

采用传统DAO开发方式进行MyBatis与Spring框架整合是,我们需要编写DAO接口以及接口的实现类,并且需要向DAO接口实现类中注入SqlSessionFactory,然后在方法体内通过SQLSessionFactory创建SqlSession。我们可以使用mybatis-spring包中所提供的SqlSessionTemplate或SqlSessionDaoSupport类来实现此功能
SqlSessionTemplate:是mybatis-spring的核心类,负责管理MyBatis的SqlSession调用MyBatis的SQL方法,当调用SQL方法时,SqlSessionTemplate将会保证使用SqlSession和当前事务是相关的,还管理SqlSession的生命周期。
SqlSessionDaoSupport:是一个抽象支持类,继承了DaoSupport类,主要是作为Dao的基类来使用。
示例

实现持久层

在src目录下,创建一个com.itheima.po包,并在包中创建持久化了Customer,在Customer类中定义相关属性和方法

package com.itheima.po;

public class Customer {
		private Integer id;
		private String username;
		private String jobs;
		private String phone;
		public Integer getId(){
			return id;
		}
		public void setId(Integer id){
			this.id=id;
		}
		public String getUsername(){
			return username;
		}
		public void setuserName(String username){
			this.username=username;
		}
		public String getJobs(){
			return jobs;
		}
		public void setJobs(String jobs){
			this.jobs=jobs;
		}
		public String getPhone(){
			return phone;
		}
		public void setPhone(String phone){
			this.phone=phone;
		}
		public String toString(){
			return "Customer [id="+id+",username="+username+",jobs="+jobs+",phone="+phone+"]";
		}
}

(2)在com.itheima.po包中,创建映射文件C苏Tom而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">
<mapper namespace="com.itheima.po.CustomerMapper">
	<select id="findCustomerById" parameterType="Integer" resultType="customer">
		select *from t_customer where id=#{id}
	</select>
</mapper>

(3)在MyBatis的配置文件mybatis-config.xml中,配置映射文件CustomerMapper.xml的位置

<mapper resource="com/itheima/po/CustomerMapper.xml"/>
实现DAO层

(1)在src目录下创建一个com.itheima.dao的包,并在包中创建接口CustomerDao,在接口中编写通过id查询的方法
CustomerDao

package com.itheima.dao;
import com.itheima.po.*;
public interface CustomerDao {
	public Customer findCustomerById(Integer id);
}

CustomerDaoImpl

package com.itheima.impl;
import com.itheima.dao.*;
import com.itheima.po.*;
import org.mybatis.spring.support.SqlSessionDaoSupport;
public class CustomerDaoImpl extends SqlSessionDaoSupport implements CustomerDao{
	public Customer findCustomerById(Integer id){
		return this.getSqlSession().selectOne("com.itheima.po"+".CustomerMapper.findCustomerById",id);
	}
}

(2)在Spring的配置文件applicationContext.xml中,编写实例化CustomerDaoImpl的配置

<bean id="customerDao" class="com.itheima.impl.CustomerDaoImpl">
        	<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>
整合测试

在Src目录下创建一个com.itheima.test包,创建测试类

package com.itheima.test;
import com.itheima.po.*;
import com.itheima.dao.*;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DaoTest {
	@Test
	public void findCustomerByIdDaoTest(){
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
		CustomerDao customerDao=(CustomerDao) applicationContext.getBean("customerDao");
		Customer customer=customerDao.findCustomerById(1);
		System.out.println(customer);
	}
}

在这里插入图片描述

Mapper接口方式开发整合

基于MapperFactoryBean的整合

MapperFactoryBean是MyBatis-Spring团队提供的一个英语根据Mapper接口生成Mapper对象的类,该类在Spring配置文件中使用时可以配置以下参数
mapperInterface:用于指定接口
sqlSessionFactory:用于指定SqlSessionFactory
sqlSessionFactory:用于指定SqlSessionTemplate。
示例:
(1)在src目录下创建一个com.itheima.mapper包,然后在该包下创建CustomerMapper接口以及对应的映射文件
Customer.java

package com.itheima.mapper;
import com.itheima.po.*;
public interface CustomerMapper {
	public Customer findCustomerById(Integer id);
}

CustomerMapper.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.itheima.mapper.CustomerMapper">
	<select id="findCustomerById" parameterType="Integer" resultType="customer">
		select *from t_customer where id=#{id}
	</select>
</mapper>

(2)在MyBatis的配置文件中引入映射文件

<mapper resource="com/itheima/mapper/CustomerMapper.xml"/>

(3)在Spring的配置文件中,创建一个id为customerMapper的Bean

<bean id="customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        	<property name="mapperInterface" value="com.itheima.mapper.CustomerMapper"/>
        	<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>

(4)编写新的测试方法

@Test
	public void findCustomerByIdMapperTest(){
		ApplicationContext act=new ClassPathXmlApplicationContext("applicationContext.xml");
		CustomerMapper customerMapper=(CustomerMapper) act.getBean("customerMapper");
		Customer customer=customerMapper.findCustomerById(1);
		System.out.println(customer);
	}

在这里插入图片描述

基于MapperScannerConfigurer的整合

MyBatis-Spring团队提供了一种自动扫描的形式来配置MyBatis中的映射器——采用MapperScannerConfig类
MapperScannerConfigurer类在Spring配置文件中使用时可以配置以下几个属性
1.basePackage:指定映射接口文件所在的包路径,需要扫描多个包时可以使用分号或逗号作为分隔符
2.annotationClass:指定了要扫描的注解名称,只有被注解才会被配置成映射器。
3.sqlSessionFactoryBeanName:指定在Spring中定义的SqlSessionFactory的Bean名称
4.sqlSessionTemplateBeanName:指定在Spring中定义的SqlSessionTemplate的Bean名称。如果定义该名称sqlSessionFactoryBeanName将不起作用
5.markerInterface:指定创建映射器接口
MapperScannerConfigure的使用示例,只需在Spring的配置文件中编写

<bean class="org.mybatis.spring.mapper.MapperScannerConfigured">
	<property name="basePackage" value="com.itheima.Mapper">
</bean>

测试事务

业务层既是处理业务的地方,又是管理数据库事务的地方,要对事务进行测试,首先要创建业务层,并在业务层编写添加客户操作的代码;然后在添加操作的代码后,有意的添加错误代码来模拟现实中的意外,最后编写测试方法,调用业务层的添加方法。
示例:
(1)在CustomerMapper接口中编写测试方法addCustomer(),代码如下

public void addCustomer(Customer customer);

在映射文件CustomerMapper.xml中编写执行插入操作的SQL代码

<insert id="addCustomer" parameterType="customer">
		insert into t_customer(username,jobs,phone)
		values(#{username},#{jobs},#{phone})
	</insert>

(2)在src目录下创建一个com.itheima.service.impl包,并在包中创建CustomerService接口实现类CustomerServiceImpl来实现接口的方法

package com.itheima.service.impl;
import org.springframework.transaction.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

import com.itheima.mapper.CustomerMapper;
import com.itheima.po.*;
import com.itheima.service.*;
import org.mybatis.spring.support.SqlSessionDaoSupport;
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService{
	@Autowired
	private CustomerMapper customerMapper;
	public void addCustomer(Customer customer) {
		this.customerMapper.addCustomer(customer);
		int i=1/0;
	}
	
}

(4)在spring的配置文件中,编写开启注解扫描的配置代码

<context:component-scan base-package="com.itheima.service"/>

(5)编写测试代码

@Test
	public void TransactionTest(){
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
		CustomerService customerService=applicationContext.getBean(CustomerService.class);
		Customer customer=new Customer();
		customer.setuserName("zhangsan");
		customer.setJobs("manager");
		customer.setPhone("133233334444");
		customerService.addCustomer(customer);
	}

在这里插入图片描述
在这里插入图片描述
没有进行插入操作,说明项目中的事务操作配置正确。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值