MyBatic与Spring的整合,传统DAO方式的开发

本文摘自:Java EE企业级应用开发教程,有部分修改

一、整合环境搭建

1、准备JAR包

Spring框架所需的JAR包(注意:不一定是MyBatis必须要用这些包,而是作为整体开发环境,这些包是必须的)

springaspectj_lib(用户类库名,自定义的)
    aopalliance-1.0.jar        AspectJ包(三个)
    aspectjrt-1.9.5.jar
    aspectjweaver-1.8.7.jar

springcore_lib(用户类库名,自定义的)
    commons-logging-1.2.jar        Spring需要用它记录日志(第三方包)
    spring-beans-5.2.3.RELEASE.jar    SpringIoC(依赖注入)的基础实现
    spring-context-5.2.3.RELEASE.jar    Spring提供在基础IoC功能上的扩展服务,如邮件服务、任务调度、JNDI定位、EJB集成、远程访问、缓存以及各种视图层框架的封装等
    spring-core-5.2.3.RELEASE.jar        Spring核心包
    spring-expression-5.2.3.RELEASE.jar    Spring表达式语言
    spring-aop-5.2.3.RELEASE.jar        Spring的面向切面编程,提供AOP(面向切面编程)实现

springjdbc_lib(用户类库名,自定义的)
    spring-jdbc-5.2.3.RELEASE.jar        JDBC驱动包
    spring-tx-5.2.3.RELEASE.jar        事务管理

 MyBatis模板框架所需JAR包

mybatis_lib(用户类库名,自定义的)
    mybatis-3.2.0.jar
    ant-1.10.3.jar
    ant-launcher-1.10.3.jar
    asm-3.3.1.jar
    cglib-2.2.2.jar
    commons-logging-1.2.jar(可能有重复)
    javassist-3.17.1-GA.jar(可能有重复)
    log4j-1.2.17.jar(可能有重复,一系列3个)
    log4j-api-2.11.2.jar
    log4j-core-2.11.2.jar
    ognl-3.2.10.jar
    slf4j-api-1.7.26.jar(可能有重复,一系列2个)
    slf4j-log4j12-1.7.2.jar

MyBatis与Spring整合的中间JAR包、数据库驱动JAR包(MySQL),数据源所需JAR包(连接池)

mybatis-spring-1.3.1.jar
mysql-connector-java-5.1.49-bin.jar
commons-dbcp2-2.1.1.jar 数据源所需
commons-pool2-2.4.2.jar 数据源所需

mybatis-spring-1.3.1.jar下载链接:https://pan.baidu.com/s/1aDfoYdUikOkp8pFQoeE0HA  提取码:boer

2、编写配置文件

2.1 db.properties

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

2.2 applicationContext-mybatis.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-spring.xml"/>
      </bean>
   
    <!--实例化Dao,此部分是与下面的样例结合在一起的 -->
    <bean id="customerDao" class="com.itheima.dao.impl.CustomerDaoImpl">
        <!-- 注入SqlSessionFactory对象实例-->
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
</beans>

配置文件中,首先定义读取properties文件的位置;然后配置数据源;接下来配置事务管理器并开启事务注解;最后配置MyBatis工厂来与Spring整合。MyBatis工厂的作用,就是构建SqlSessionFactory,它是通过mybatis-spring包中提供的org.mybatis.spring.SqlSessionFactoryBean类来配置的。

最后实例化Dao部分,是与下面的Dao样例结合在一起的。

2.3 mybatis-config-spring.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>
    <!--配置Mapper的位置 -->
    <mappers> 
       <mapper resource="com/itheima/po/CustomerMapper.xml" />
    </mappers>
</configuration>

同样,此部分包括样例的配置。

二、传统DAO方式的开发整合

1、创建表结构与导入数据

CREATE TABLE `t_customer` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `USERNAME` varchar(45) NOT NULL,
  `JOBS` varchar(45) DEFAULT NULL,
  `PHONE` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `t_customer` (`ID`,`USERNAME`,`JOBS`,`PHONE`) VALUES (1,'张三','测试工程师','13099992222');
INSERT INTO `t_customer` (`ID`,`USERNAME`,`JOBS`,`PHONE`) VALUES (2,'李四','开发工程师','13900002222');
INSERT INTO `t_customer` (`ID`,`USERNAME`,`JOBS`,`PHONE`) VALUES (3,'赵五','美工','12899998888');

2、实现持久层

2.1 Customer实体类代码:

package com.itheima.po;

import lombok.Data;

@Data
public class Customer {
    private Integer id;       // 主键id
    private String username; // 客户名称
    private String jobs;      // 职业
    private String phone;     // 电话
}

注意:为保持代码的简洁,实体类引用到lombok.jar;有需要下载的,请参考链接:https://pan.baidu.com/s/1pbcFiBRoytgRK6asLAl-Cg  提取码:s75p

如果此包在IDE开发环境中出现问题,请参考:lombok的@Data/@ToString注解不生效:MyEclipse2020环境下,如何正确安装lombok

2.2 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.po.CustomerMapper">
    <!--根据id查询客户信息 -->
    <select id="findCustomerById" parameterType="Integer"
             resultType="customer">
        select * from t_customer where id = #{id}
    </select>
</mapper>

注意:此Mapper文件,与实体类位于同一个目录。

2.3 在mybatis-config-spring.xml配置文件中增加相关代码

本文上面已经增加,故不需要额外操作。

3、实现DAO层

3.1 CustomerDao类参考:

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

3.2 CustomerDaoImpl实现类参考:

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

说明:CustomerDaoImpl类,继承SqlSessionDaoSupport类,并实现CustomerDao接口。SqlSessionDaoSupport类在使用时,需要一个SqlSessionFactory或一个SqlSessionTemplate对象,它是通过Spring给SqlSessionDaoSupport的子类对象注入的。

4、整合测试

package com.itheima.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.itheima.dao.CustomerDao;
import com.itheima.po.Customer;

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

输出结果:

DEBUG [main] - ==>  Preparing: select * from t_customer where id = ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
Customer(id=1, username=张三, jobs=测试工程师, phone=13099992222)

 

posted @ 2021-09-14 11:54  那些年的事儿  阅读(155)  评论(0编辑  收藏  举报