21.传统DAO方式的开发整合

1.整合环境搭建

1.1 准备jar包

1.Spring框架所需的JAR包
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

1.2 编写配置文件

1.创建项目(chapter10),引入JAR包
2.编写db.properties

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

3.编写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: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-4.3.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
    <!--读取db.properties -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 配置数据源 -->
	<bean id="dataSource" 
            class="org.apache.commons.dbcp2.BasicDataSource">
        <!--数据库驱动 -->
        <property name="driverClassName" value="${jdbc.driver}" />
        <!--连接数据库的url -->
        <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"/>
    <!--配置MyBatis工厂 -->
    <bean id="sqlSessionFactory" 
            class="org.mybatis.spring.SqlSessionFactoryBean">
         <!--注入数据源 -->
         <property name="dataSource" ref="dataSource" />
         <!--指定核心配置文件位置 -->
   		<property name="configLocation" value="classpath:mybatis-config.xml"/>
   </bean>	   	
</beans>

4.编写MyBatis配置文件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="cn.lctvu.po" />
    </typeAliases>
    <!--配置Mapper的位置 -->
	<mappers>      
       
	</mappers>
</configuration>

由于在Spring中已经配置了数据源信息,所以在MyBatis的配置文件中就不再需要配置数据源信息。
5.引入log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.itheima=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

2.传统DAO方式的开发整合

采用传统DAO开发方式进行MyBatis与Spring框架的整合时,我们需要编写DAO接口以及接口的实现类,并且需要向DAO实现类中注入SqlSessionFactory,然后在方法体内通过SqlSessionFactory创建SqlSession。为引可以使用mybatis-spring包中所提供的SqlSessionTemplate类或SqlSessionDaoSupport类来实现。

SqlSessionTemplate:是mybatis-spring的核心类,它负责管理MyBatis的SqlSession,调用MyBatis的SQL方法。当调用SQL方法时,SqlSessionTemplate将会保证使用的SqlSession和当前Spring的事务是相关的。它还管理SqlSession的生命周期,包含必要的关闭、提交和回滚操作。
SqlSessionDaoSupport:是一个抽象支持类,它继承了DaoSupport类,主要是作为DAO的基类来使用。可以通过SqlSessionDaoSupport类的getSqlSession()方法来获取所需的SqlSession。

2.1 传统DAO开发实现过程

2.1.1 实现持久层

1.创建包cn.lctvu.po,在该包中创建Customer.java

/**
 * 客户持久化类
 */
public class Customer {
	private Integer id;       // 主键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;
	}
	@Override
	public String toString() {
		return "Customer [id=" + id + ", username=" + username + 
				       ", jobs=" + jobs + ", phone=" + phone + "]";
	}
}

2.在cn.lctvu.po包中创建映射文件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="cn.lctvu.po.CustomerMapper">
	<!--根据id查询客户信息 -->
	<select id="findCustomerById" parameterType="Integer"
		     resultType="customer">
		select * from t_customer where id = #{id}
	</select>
</mapper>

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

<!--配置Mapper的位置 -->
	<mappers>
       <mapper resource="cn/lctvu/po/CustomerMapper.xml"/>
	</mappers>
2.1.2 实现DAO层

1.在src目录下,创建一个cn.lctvu.dao包,并在包中创建接口CustomerDao,在接口中编写一个通过id查询客户的方法findCustomerById()
CustomerDao.java

package cn.lctvu.dao;
import cn.lctvu.po.Customer;
public interface CustomerDao {
	// 通过id查询客户
	public Customer findCustomerById(Integer id);
}

2.在cn.lctvu.dao下再创建impl包,并在包中创建CustomerDao接口的实现类CustomerDaoImpl

public class CustomerDaoImpl
		extends SqlSessionDaoSupport implements CustomerDao {
	// 通过id查询客户
	public Customer findCustomerById(Integer id) {
         	return this.getSqlSession().selectOne("cn.lctvu.po"
				      + ".CustomerMapper.findCustomerById", id);
	}
}

CustomerDaoImpl类继承了SqlSessionDaoSupport类,并实现了CustomerDao接口。其中,SqlSessionDaoSupport类在使用时需要一个SqlSessionFactory或一个SqlSessionTemplate对象,所以需要通过Spring给SqlSessionDaoSupport类的子类对象注入一个SqlSessionFactory或SqlSessionTemplate。这样,在子类中就能通过调用SqlSessionDaoSupport类的getSqlSession()方法来获取SqlSession对象,并使用SqlSession对象 中的方法了。
3.在Spring的配置文件applicationContext.xml中,编写实例化CustomerDaoImpl的配置,代码如下:

<!--实例化Dao -->
	<bean id="customerDao" class="cn.lctvu..dao.impl.CustomerDaoImpl">
		<!-- 注入SqlSessionFactory对象实例-->
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>
2.1.3 整合测试

在src目录下创建一个cn.lctvu.test包,在包中创建测试类DaoTest,并在类中编写测试方法findCustomerByIdDaoTest()

/**
 * DAO测试类
 */
public class DaoTest {
	@Test
	public void findCustomerByIdDaoTest(){
		ApplicationContext act = 
		    new ClassPathXmlApplicationContext("applicationContext.xml");
          // 根据容器中Bean的id来获取指定的Bean
	     CustomerDao customerDao =
                              (CustomerDao) act.getBean("customerDao");
//	     CustomerDao customerDao = act.getBean(CustomerDao.class);
		 Customer customer = customerDao.findCustomerById(1);
		 System.out.println(customer);
	}
}

在上述方法中,我们采用的是根据容器中Bean的Id来获取指定Bean的方式。我们还可以根据类的类型来获取Bean的实例:
CustomerDao customerDao = act.getBean(CustomerDao.class);
采用此种方式,就不再需要进行强制类型转换了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

聊城云在天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值