mybatis與spring整合,三種開發方式原始Dao開發,Mapper代理以及Mapper代理增強版開發

一.原始Dao開發

   1.創建pojo


package cn.liang.pojo;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
		private static final long serialVersionUID = 1L;
		private int id;
		private String username;// 用戶姓名
		private String sex;// 性別
		private Date birthday;// 生日
		private String address;// 地址
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getUsername() {
			return username;
		}
		@Override
		public String toString() {
			return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday
					+ ", address=" + address + "]";
		}
		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;
		}

}

2.實現Mapper.xml

編寫User.xml配置文件,如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTDMapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
    <!--根據用戶id查詢 -->
    <select id="queryUserById" parameterType="int"resultType="user">
       select * from user where id = #{id}
    </select>
    <!--根據用戶名模糊查詢用戶 -->
    <select id="queryUserByUsername" parameterType="string"
       resultType="user">
       select * from user where username like '%${value}%'
    </select>
    <!--添加用戶 -->
    <insert id="saveUser" parameterType="user">
       <selectKey keyProperty="id" keyColumn="id" order="AFTER"
           resultType="int">
           select last_insert_id()
       </selectKey>
       insert into user
       (username,birthday,sex,address)
       values
       (#{username},#{birthday},#{sex},#{address})
    </insert>
</mapper>

3.加載Mapper.xml

在SqlMapConfig如下進行配置:

<mappers>
		<mapper resource="cn/liang/mapper/UserMapper.xml"/>
	</mappers>

4. 實現UserDao接口

publicinterface UserDao {
    public User selectUserById(Integer id);
    public List<User> selectUserByUsername(User user);
    public void saveUser(User user);
}

5. 實現UserDaoImpl實現類

編寫DAO實現類,實現類必須繼承SqlSessionDaoSupport

SqlSessionDaoSupport提供getSqlSession()方法來獲取SqlSession

package cn.liang.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import cn.liang.pojo.User;

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
	
	public User selectUserById(Integer id) {
	
		SqlSession sqlSession = this.getSqlSession();
		User user = sqlSession.selectOne("findUserById", id);
		return user;
	}

	public List<User> selectUserByUsername(User user) {
		SqlSession sqlSession = this.getSqlSession();
		
		List<User> users = sqlSession.selectList("findUserByUsername", user);
		return users;
	}

	@Override
	public void saveUser(User user) {
		SqlSession sqlSession = this.getSqlSession();
		sqlSession.insert("addUser", user);
		
	}

}

6.配置applicationContext文件

把dao實現類配置到spring容器中,如下

<?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="dataSource" 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="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置mybatis核心配置文件 -->
        <property name="configLocation" value="classpath:SqlMapConfig.xml" />
        <!-- 配置數據源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 原始Dao開發 -->
    <bean id="userDao" class="cn.liang.dao.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
    
    <!-- Mapper動態代理開發 -->
    
    <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
        <property name="mapperInterface" value="cn.liang.mapper.UserMapper"></property>
    </bean>  -->
    
    <!-- Mapper動態代理開發增強版 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 不需要注入sqlSessionFactory -->
        <property name="basePackage" value="cn.liang.mapper"></property>
    </bean>
</beans>



7. 測試方法

創建測試方法,可以直接創建測試Junit用例

package cn.liang.test;

import java.util.Date;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.liang.dao.UserDao;
import cn.liang.dao.UserDaoImpl;
import cn.liang.pojo.User;

public class testUserDao {
	private ApplicationContext context;

	@Before
	public void setUp() throws Exception {
		this.context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
	}

	@Test
	public void testQueryUserById() {
		// 獲取userDao
		UserDao userDao = this.context.getBean(UserDao.class);

		User user = userDao.selectUserById(1);
		System.out.println(user);
	}

	@Test
	public void testQueryUserByUsername() {
		// 獲取userDao
		UserDaoImpl userDao = (UserDaoImpl) context.getBean("userDao");
		User user=new User();
		user.setUsername("張");

		List<User> list = userDao.selectUserByUsername(user);
		for (User u : list) {
			System.out.println(u);
		}
	}

	@Test
	public void testSaveUser() {
		// 獲取userDao
		UserDao userDao = this.context.getBean(UserDao.class);

		User user = new User();
		user.setUsername("曹操");
		user.setSex("1");
		user.setBirthday(new Date());
		user.setAddress("三國");
		userDao.saveUser(user);
		System.out.println(user);
	}

}

二.Mapper代理開發

在applicationContext.xml文件中添加配置,如下

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
		<property name="mapperInterface" value="cn.liang.mapper.UserMapper"></property>
</bean>

在mapper包下書寫接口UserMapper

package cn.liang.mapper;
import java.util.List;
import cn.liang.pojo.User;
public interface UserMapper {
	public User findUserById(Integer id);
	public List<User> findUserByUsername(User user);
	public void addUser(User user);

}

進行測試

package cn.liang.test;

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

import cn.liang.mapper.UserMapper;
import cn.liang.pojo.User;

public class TestUserMapper {


	private ApplicationContext context;
	@Test
	public void test(){
		context=new 
				ClassPathXmlApplicationContext("classpath:applicationContext.xml");
		UserMapper userMapper = (UserMapper) context.getBean("userMapper");
//		UserMapper userMapper = context.getBean(UserMapper.class);
		User user = userMapper.findUserById(1);
		System.out.println(user);
	}
}

三.Mapper代理增強版開發

增強版是採用掃描的方式實現的

在applicationContext.xml中將普通Mapper代理方式的文件註釋掉,添加新的如下

<!-- Mapper動態代理開發增強版 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 不需要注入sqlSessionFactory -->
		<property name="basePackage" value="cn.liang.mapper"></property>
	</bean>

然後在測試代碼中,獲取代理類的方法不同,參數是接口的字節碼對象

//		UserMapper userMapper = (UserMapper) context.getBean("userMapper");
		UserMapper userMapper = context.getBean(UserMapper.class);

其他地方不用修改,同普通Mapper代理開發相同






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章