1. 程式人生 > >MyBatis與Spring整合的兩種方式

MyBatis與Spring整合的兩種方式

1、第一步:匯入jar包

spring的jar包、Mybatis的jar包、Spring+mybatis的整合包、Mysql的資料庫驅動jar包、資料庫連線池的jar包

2、加入配置檔案:

Spring的配置檔案——applicationContext.xml

這裡有一點需要注意:在配置sqlSessionFactory工廠時,在注入資料庫連線池的時候property的屬性名是dataSource,不要亂寫(很容易寫成dataSourse),否則會報如下錯誤:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactoryBean' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSourse'ofbean class [org.mybatis.spring.SqlSessionFactoryBean]: Bean property 'dataSourse' is not writable or has an invalid setter method. Did you mean'dataSource'?

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	<!-- 載入資料庫配置檔案 -->
	<context:property-placeholder location="classpath:db.properties"/>
	
    <!-- 資料庫連線池 -->
    <bean id="dataSourse" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    	<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="maxActive" value="10"/>
		<property name="maxIdle" value="5"/>
    </bean>
    <!-- 配置SQLSessionFactory -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置mybatis核心配置檔案 -->
    	<property name="configLocation" value="sqlMapConfig.xml"/>
    	<!-- 注入連線池 -->
    	<property name="dataSource" ref="dataSourse"/>
    </bean>

	<!-- 配置Dao 原始dao開發-->
	<bean id="UserDao" class="com.qianjin.dao.UserDaoImpl">
	  	<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
	</bean>
	<!-- Mapper動態代理 -->
	<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<!-- 注入工廠 -->
		<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
		<!-- 注入介面 -->
		<property name="mapperInterface" value="sqlmapper.UserMapper"/>
	</bean>
</beans>

MyBatis的配置檔案——sqlMapConfig.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>
		<!-- 2. 指定掃描包,會把包內所有的類都設定別名,別名的名稱就是類名,大小寫不敏感 -->
		<package name="com.qianjin.pojo"/>
	</typeAliases>
	
	<mappers>
		<package name="sqlmapper"/>
	</mappers>
	
</configuration>

連結資料庫的配置資訊檔案——db.property

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

3、Dao開發:有兩種形式。一種是傳統的DAO開發,另一種是Mapper動態代理開發

(1)傳統Dao開發

pojo類:

package com.qianjin.pojo;

import java.util.Date;

public class User{
	private Integer id;
	private String username;// 使用者姓名
	private String sex;// 性別
	private Date birthday;// 生日
	private String address;// 地址
	
	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 getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
				+ address + "]";
	}

}
package com.qianjin.dao;

import com.qianjin.pojo.User;

public interface UserDao {
	User queryUserById(Integer id);
}
package com.qianjin.dao;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.qianjin.pojo.User;

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{

	@Override
	public User queryUserById(Integer id) {
		User user = this.getSqlSession().selectOne("queryUserById", 10);
		return user;
	}
	

}

測試執行:

package com.qianjin.dao.test;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.qianjin.dao.UserDao;
import com.qianjin.pojo.User;
public class UserDaoTest {
	ApplicationContext context;
	@Before
    public void init(){
    	 this.context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    }
	@Test
	public void testQueryUserById(){
		UserDao userDao=this.context.getBean(UserDao.class);
		User user = userDao.queryUserById(10);
		System.out.println(user);
		
	}
}

(2)Mapper動態代理開發(UserMapper介面和UserMapper.xml配置檔案要在同一個包下)

配置UserMapper介面:

package sqlmapper;

import com.qianjin.pojo.User;

public interface UserMapper {
	User queryUserById(Integer id);
}

配置UserMapper.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="sqlmapper.UserMapper">
	<!-- 根據使用者id查詢 -->
	<select id="queryUserById" parameterType="Integer" resultType="user">
		select * from user where id = #{id}
	</select>
</mapper>

在Spring的配置檔案applicationContext.xml中配置UserMapper的配置資訊(上面的程式碼中已經配置,此處再貼一遍)

<!-- Mapper動態代理 -->
	<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<!-- 注入工廠 -->
		<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
		<!-- 注入介面 -->
		<property name="mapperInterface" value="sqlmapper.UserMapper"/>
	</bean>

寫測試類進行測試:

package com.qianjin;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.qianjin.pojo.User;

import sqlmapper.UserMapper;

public class JunitTest {
	private ApplicationContext context;
	@Before
	public void init() {
		//通過類路徑配置spring配置檔案的位置資訊
		this.context=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
	}
	@Test
	public void testQueryUserById() {
		//根據spring配置檔案獲取bean
		UserMapper userMapper = (UserMapper) this.context.getBean("userMapper");
		User user = userMapper.queryUserById(10);
		System.out.println(user);
	}
}