JavaEE Spring与MyBatis的整合之传统DAO方式整合(教材学习笔记)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40788630/article/details/83713975

在实际开发中MyBatis都是与Spring整合在一起使用的,在之前学习了MyBatis与Spring,现在来学习如何使他们整合

首先创建一个名为chapter10的web项目

一、环境搭建

1.准备好所有的有关jar包,具体如下:

将上面所有jar包添加到项目lib目录下,并发布到类路径下 

2.编写配置文件

在src目录下创建db.properties文件,Spring配置文件以及MyBatis的配置文件,三个文件分别如下所示:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=itcast
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5
<?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">
    <!-- 读取dp.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>
        <!-- 指定核心配置文件位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>
    
    <bean id="CustomerDao" class="com.itheima.dao.impl.CustomerDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>
<?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>

    <properties resource="db.properties"/>
    <typeAliases>
        <package name="com.itheima.po"/>
    </typeAliases>
    
    <mappers>
        
        
    </mappers>
</configuration>

3.此外还需要创建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

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

1.在src目录下创建com.itheima.po包,并在包中创建持久化类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;
	}
	@Override
	public String toString() {
		return "Customer [id="+id+",username="+username+",jobs="+jobs+",phone="+phone+"]";
	}
	

}

2.在com.itheima.po包中,创建映射文件CustomerMapper.xml在该文件下编写根据id查询的映射语句

<?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中,配置映射文件Customer.xml的位置,具体如下:

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

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

package com.itheima.dao;

import com.itheima.po.Customer;

public interface CustomerDao {
    public Customer findCustomerById(Integer id);
}

5.在src目录下创建一个com.itheima.dao.impl包,并在包中创建接口CustomerDao的实现类

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 {

	@Override
	public Customer findCustomerById(Integer id) {
		return this.getSqlSession().selectOne("com.itheima.po.CustomerMapper.findCustomerById",id);
	}

}

6.在spring的配置文件中,编写实例化CustomerDaoImpl的配置,并将SqlSessionFactory对象注入之中

<bean id="CustomerDao" class="com.itheima.dao.impl.CustomerDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

7、整合测试,在src目录下创建com.itheima.test包,并在包中创建测试类DaoTest类,在类中编写测试方法findCustomerByIdDaoTest()

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;

public class DaoTest {
	@Test
	public void findCustomerByIdTest() {
		ApplicationContext act= new ClassPathXmlApplicationContext("applicationContext.xml");
		CustomerDao customerDao = act.getBean(CustomerDao.class);
		Customer customer = customerDao.findCustomerById(1);
		System.out.println(customer);
	}

}

8.测试结果如下:

和数据库进行对比

猜你喜欢

转载自blog.csdn.net/qq_40788630/article/details/83713975