Mybatis 學習筆記(二)——原生DAO實現資料增刪改查

lytao123發表於2018-10-13

一、開發環境

  1. JDK
    java version “1.8.0_171”
    Java™ SE Runtime Environment (build 1.8.0_171-b11)
    Java HotSpot™ 64-Bit Server VM (build 25.171-b11, mixed mode)
  2. Eclipse
    Eclipse Java EE IDE for Web Developers.
    Version: Oxygen.3a Release (4.7.3a)
  3. MySQL
    其中的資料庫檔案在地址:點選下載
  4. Mybatis
    mybatis-3.4.6

二、專案結構

專案結構

三、編寫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>
	<!-- 載入屬性檔案 -->
	<properties resource="config/db.properties"></properties>

	<!-- 定義別名 -->
	<typeAliases>
		<!-- 針對批量別名定義,別名就是類名(首字母大小寫都可以) -->
		<package name="com.po"/>
	</typeAliases>
	
	<!-- 和Spring整合後environments配置將廢除 -->
	<environments default="development">
		<environment id="development">
			<!-- 使用JDBC事務管理,事務控制由mybatis管理 -->
			<transactionManager type="JDBC" />
			<!-- 資料庫連線池,由mybatis管理 -->
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>

	<!-- 載入對映檔案 -->
	<mappers>
		<!-- 通過resource載入 -->
		<mapper resource="config/sqlmap/User.xml" />
	</mappers>
</configuration>

db.properties檔案內容為:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456

四、編寫User.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">

<!-- namespace:名稱空間,作用是對sql進行分類化管理, 注意:在mapper代理方法開發, namespace有特殊作用 -->
<mapper namespace="test">
	<select id="findUserById" parameterType="int" 
		resultType="user">
		SELECT * FROM USER WHERE ID = #{id}
	</select>
	
	<select id="findUserByName" parameterType="java.lang.String"
		resultType="user">
		SELECT * FROM USER WHERE USERNAME LIKE '%${value}%'
	</select>
	
	<insert id="insertUser" parameterType="user">
		<!-- 
			將插入的主鍵返回到user物件中 
			SELECT LAST_INSERT_ID():得到將insert進去的記錄的主鍵值,只適用與自增主鍵
			keyProperty:將查詢到的主鍵設定到parameterType指定的物件的哪個屬性
			order:SQL語句執行的順序,BEFORE或AFTER
		-->
		<selectKey keyProperty="id" order="AFTER" resultType="int">
			SELECT LAST_INSERT_ID()
		</selectKey>
		INSERT INTO USER(USERNAME,SEX,BIRTHDAY,ADDRESS) VALUES(#{username},#{sex},#{birthday},#{address})
	</insert>
	
	<delete id="deleteUser" parameterType="int">
		DELETE FROM USER WHERE ID = #{id}
	</delete>
	
	<update id="updateUser" parameterType="user">
		UPDATE USER 
		SET USERNAME = #{username}, SEX = #{sex}, BIRTHDAY = #{birthday}, ADDRESS = #{address}
		WHERE ID = #{id}
	</update>
</mapper>

五、編寫介面UserDao.java

package com.dao;

import java.util.List;

import com.po.User;

/**
 * 描述:原生dao介面,管理使用者
 * @author 歐陽
 * @since 2018年10月9日
 */
public interface UserDao {
	
	//根據id查詢使用者資訊
	public User findUserById(int id) throws Exception;
	
	//根據username查詢使用者資訊
	public List<User> findUserByName(String name) throws Exception;
	
	//插入使用者資訊
	public void insertUser(User user) throws Exception;
	
	//更新使用者資訊
	public void updateUser(User user) throws Exception;
	
	//根據id刪除使用者資訊
	public void deleteUserById(int id) throws Exception;
}

六、實現介面UserDaoImpl.java

package com.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.po.User;

/**
 * 描述:原生dao開發實現類
 * @author 歐陽
 * @since 2018年10月9日
 */
public class UserDaoImpl implements UserDao {
	//通過建構函式注入SqlSessionFactory
	private SqlSessionFactory  sqlSessionFactory;
	public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
		super();
		this.sqlSessionFactory = sqlSessionFactory;
	}
	
	@Override
	public User findUserById(int id) throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		User user = sqlSession.selectOne("test.findUserById", id);
		sqlSession.close();
		return user;
	}
	
	@Override
	public List<User> findUserByName(String name) throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		List<User> user = sqlSession.selectList("test.findUserById", name);
		sqlSession.close();
		return user;
	}

	@Override
	public void insertUser(User user) throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		sqlSession.insert("test.insertUser", user);
		sqlSession.commit();
		sqlSession.close();
	}

	@Override
	public void deleteUserById(int id) throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		sqlSession.delete("test.deleteUser", id);
		sqlSession.commit();
		sqlSession.close();
	}

	@Override
	public void updateUser(User user) throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		sqlSession.insert("test.updateUser", user);
		sqlSession.commit();
		sqlSession.close();
	}

}


七、測試

package com.dao;

import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import com.po.User;

public class UserDaoImplTest {
	
	private SqlSessionFactory  sqlSessionFactory;
	//此方法是在執行testFindUserById之前執行
	@Before
	public void setUp() throws Exception {
		String resource = "config/SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);

		// 建立會話工廠
		this.sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(inputStream);
	}
	
	@Test
	public void testFindUserById() {
		UserDao userDao = new UserDaoImpl(this.sqlSessionFactory);
		try {
			User user = userDao.findUserById(2);
			System.out.println(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testFindUserByName() {
		UserDao userDao = new UserDaoImpl(this.sqlSessionFactory);
		try {
			List<User> users = userDao.findUserByName("小");
			System.out.println(users.size());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testInsertUser() {
		UserDao userDao = new UserDaoImpl(this.sqlSessionFactory);
		try {
			//插入使用者物件
			User user = new User();
			user.setUsername("王小姐");
			user.setAddress("中國");
			
			userDao.insertUser(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testDeleteUserById() {
		UserDao userDao = new UserDaoImpl(this.sqlSessionFactory);
		try {
			userDao.deleteUserById(17);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@Test
	public void testUpdateUser() {
		UserDao userDao = new UserDaoImpl(this.sqlSessionFactory);
		try {
			//插入使用者物件
			User user = new User();
			user.setId(3);
			user.setUsername("王小姐");
			user.setAddress("中國");
			
			userDao.updateUser(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

八、問題總結

1、在 UserDao 介面的實現類 UserDaoImpl 中,各實現方法存在大量模板方法,存在程式碼冗餘,不利於程式設計師開發和維護;

2、呼叫 sqlSession 方法時將 statement 的id硬編碼了;

3、在UserDaoImpl 類中每個實現方法中呼叫sqlSession 方法時傳入的變數,由於sqlsession方法使用泛型,即使變數型別傳入錯誤,在編譯階段也不報錯,不利於程式設計師開發。

在Mybatis 開發時使用Mapper 代理開發將解決這些問題。Mybatis 學習筆記——使用Mapper代理的方式實現資料增刪改查

相關文章