使用mybatis開發Dao的原始方法,實現根據用戶id查詢一個用戶信息 、根據用戶名稱模糊查詢用戶信息列表 、添加用戶信息等功能


1.需求

  將下邊的功能實現Dao

    根據用戶id查詢一個用戶信息

    根據用戶名稱模糊查詢用戶信息列表

    添加用戶信息

2. 原始Dao開發方法需要程序員編寫Dao接口和Dao實現類

3.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標簽中要寫很多sql語句。在開發項目的過程中有很多人都會寫Sql
語句,在最后整合的時候可能會重復。現在我們使用命名空間開進行隔離,比如zhangsan
寫的select * from user,我們可以寫為:zhangsan:select * from user來進行標識。 -->
<mapper namespace="test">
    <!-- id:sql語句的唯一標識   test:findUserById就可以唯一標識sql語句
         paremeterType:指定傳入的參數類型
         resultSetType:返回值結果類型
         #{}占位符:起到占位的左永剛,如果傳入的基本類型{String,long,double,int boolean等},那么
         #{}中的變量名稱可以隨意寫。
    -->
    <select id="findUserById" parameterType="java.lang.Integer" resultType="com.huida.po.User">
        <!-- select語句返回的是user對象,所以resultType中寫User類的全路徑 -->
        select * from user where id=#{id}
    </select>
    
    <!-- 模糊查詢
        返回結果可能為集合;如果返回結果為集合,調用selectList(),並且返回類型配置集合中的泛型。集合中存放的就是User,所以返回類型就是User類型
        ${}拼接符:字符串原樣拼接。如果傳入的基本類型{String,long,double,int boolean等},那么
        ${}中的變量名必須是value.
    -->
    <select id="findUserByUsername" parameterType="java.lang.String" resultType="com.huida.po.User">
        <!-- 模糊查詢的占位符需要進行拼接 -->
        select * from user where username like "%${value}%"
    </select>
    
    <!-- 添加 
        添加操作返回值可有可無
        #{}:如果傳入的是po類型,那么#{}中的變量名稱必須是po中對應的屬性
    -->
    <!-- <select id="insertUser" parameterType="com.huida.po.User">
        insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
    </select> -->
    <!-- 自增主鍵返回 -->
    <insert id="insertUser" parameterType="com.huida.po.User">
        <!-- selectKey將主鍵返回,需要再返回 -->
        <!-- keyProperty:將返回的主鍵放入傳入參數的id中保存。也就是最后的結果通過id保存起來
            order:當前函數相對於insert語句的執行順序,在insert前執行的是before,在insert之后執行的是after
            resultType:id的類型
         -->
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            select LAST_INSERT_ID()
        </selectKey>
        insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address});
    </insert>
</mapper>

4.Dao接口

package com.huida.dao;

import java.util.List;

import com.huida.po.User;

public interface UserDao {

    public User findUserById(Integer id);
    public List<User> findUserByUserName(String name);
}

5.Dao接口實現方法

package com.huida.dao;

import java.util.List;

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

import com.huida.po.User;

public class UserDaoImpl implements UserDao {

    //拿到工廠,才能得到Session,才能對sql語句進行處理
    private SqlSessionFactory factory;
    //通過構造方法將工廠傳入,也就是注入
    public UserDaoImpl(SqlSessionFactory factory) {
        super();
        this.factory = factory;
    }
    @Override
    public User findUserById(Integer id) {
        //創建session
        //sqlSession是線程不安全的,它的最佳使用是在方法體內
        SqlSession openSession=factory.openSession();
        User user=openSession.selectOne("test.findUserById", id);
        return user;
    }
    //模糊查詢
    @Override
    public List<User> findUserByUserName(String name) {
        //每個方法創建一個sqlSession
        SqlSession openSession=factory.openSession();
        List<User> list=openSession.selectList("test.findUserByUsername",name);
        return list;
    }
    

}

6.Dao測試

  創建一個JUnit的測試類,對UserDao進行測試。  

  這里我們使用了一個小技巧,因為沒執行一個方法都需要創建工廠,所以我們可以將創建工廠的方法拿出來,放在所有測試方法之前,並在前面加一個@Before的注解,這樣就會在測試方法前執行這個方法。不能將建了SqlSession的方法提到前面,因為SqlSession的作用范圍應該是在方法內。

 

package com.huida.test;


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.huida.dao.UserDao;
import com.huida.dao.UserDaoImpl;
import com.huida.po.User;

public class UserDaoTest {

    private SqlSessionFactory factory=null;
    //before的作用:在測試方法前執行這個方法
    @Before
    public void init() throws Exception{
        // 通過流將核心配置文件讀取進來
        InputStream inputStream = Resources.getResourceAsStream("config/SqlMapConfig.xml");
        // 通過核心配置文件輸入流來創建工廠
        factory = new SqlSessionFactoryBuilder().build(inputStream);
    }
    @Test
    public void testFindById(){
        UserDao userDao=new UserDaoImpl(factory);
        User user=userDao.findUserById(1);
        System.out.println(user);
    }
    
    @Test
    public void testFindByUserName(){
        UserDao userDao=new UserDaoImpl(factory);
        List<User> list=userDao.findUserByUserName("li");
        System.out.println(list);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM