1. 程式人生 > >JavaEE Spring與MyBatis的整合之傳統DAO方式整合(教材學習筆記)

JavaEE Spring與MyBatis的整合之傳統DAO方式整合(教材學習筆記)

在實際開發中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.測試結果如下:

和資料庫進行對比