1. 程式人生 > >使用mybatis開發原始Dao層

使用mybatis開發原始Dao層

  本文將介紹使用框架mybatis開發原始Dao層來對一個對資料庫進行增刪改查的案例。

  本次使用的mybatis版本為mybatis-3.2.7,開發工具為eclipse,資料庫為mysql,jdk版本jdk1.8.0_151。

  1、首先,使用eclipse新建一個java工程,在lib目錄下加入mybatis核心包、依賴包、資料驅動包,然後BuildPath一下。。

  

  2、新增日誌檔案,在classpath下建立log4j.properties如下:

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# 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

  3、在classpath下建立config資原始檔夾,並在config資料夾下建立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> <environments default="development"> <environment id="development"> <!-- 使用jdbc事務管理--> <transactionManager type="JDBC" /> <!-- 資料庫連線池--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> </configuration>

  SqlMapConfig.xml是mybatis核心配置檔案,上邊檔案的配置內容為資料來源、事務管理。

  4、建立資料封裝使用的User類

package com.xyfer.po;

import java.util.Date;
/**
 * 
 * @author xyfer
 * 資料封裝使用的User類
 *
 */
public class User {
    
    private int       id;          //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;
    }
    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;
    }

}

  5、在classpath下的資原始檔夾sqlmapper目錄下建立sql對映檔案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">
<mapper namespace="test">
    <!-- 根據id查詢使用者 -->
    <select id="findUserById" parameterType="int" resultType="com.xyfer.po.User">
        select * from user where id = #{id}
    </select>
    <!-- 新增使用者 -->
    <insert id="insertUser" parameterType="com.xyfer.po.User">
    <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>
    <!-- 修改使用者 -->
    <update id="updateUser" parameterType="com.xyfer.po.User">
        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
        where id=#{id}
    </update>
    <!-- 刪除使用者 -->
    <delete id="deleteUserById" parameterType="int">
        delete from user where id=#{id}
    </delete>
    
</mapper>

 

  6、mybatis框架需要載入對映檔案,將Users.xml新增在SqlMapConfig.xml,如下:

<mappers>
        <mapper resource="User.xml"/>
</mappers>

  7、dao層介面

package com.xyfer.dao;

import com.xyfer.po.User;

public interface UserDao {

    public User getUserById(int id);   //根據id值查詢一個使用者
    public void insertUser(User user); //新增一個使用者
    public void updateUser(User user); //修改一個使用者
    public void deleteUser(int id);    //刪除一個使用者
    
}

  dao層介面實現類

package com.xyfer.dao.impl;

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

import com.xyfer.dao.UserDao;
import com.xyfer.po.User;

public class UserDaoImpl implements UserDao {
    //注入SqlSessionFactory
    public UserDaoImpl(SqlSessionFactory sqlSessionFactory){
            this.setSqlSessionFactory(sqlSessionFactory);
        }
            
    private SqlSessionFactory sqlSessionFactory;
        
    public SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public User getUserById(int id) {
        SqlSession session = sqlSessionFactory.openSession();
        User user = null;
        try {
            //通過sqlsession呼叫selectOne方法獲取一條結果集
            //引數1:指定定義的statement的id,引數2:指定向statement中傳遞的引數
            user = session.selectOne("test.findUserById", 1);
            System.out.println(user);
                        
        } finally{
            session.close();
        }
        return user;
    }

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

    @Override
    public void updateUser(User user) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            sqlSession.update("test.updateUser", user);
            sqlSession.commit();
        } finally{
            sqlSession.close();
        }
    }

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

}

  8、建立一個JUnit的測試類,對UserDao進行測試。

package com.xyfer.dao.impl;

import static org.junit.Assert.*;

import java.io.InputStream;
import java.util.Date;

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

public class UserDaoImplTest {

    private SqlSessionFactory sqlSessionFactory;
    
    @Before
    public void init() throws Exception {
        SqlSessionFactoryBuilder sessionFactoryBuilder = new SqlSessionFactoryBuilder();
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        sqlSessionFactory = sessionFactoryBuilder.build(inputStream);
    }

    @Test
    public void testGetUserById() {
        UserDao userDao = new UserDaoImpl(sqlSessionFactory);
        User user = userDao.getUserById(22);
        System.out.println(user);
    }

    @Test
    public void testInsertUser() {
        User user = new User();
        user.setUsername("小李");
        user.setSex("男");
        user.setBirthday(new Date());
        user.setAddress("杭州市");
        UserDao userDao = new UserDaoImpl(sqlSessionFactory);
        userDao.insertUser(user);
    }

    @Test
    public void testUpdateUser() {
        User user = new User();
        user.setId(10);
        user.setUsername("小威");
        user.setSex("男");
        user.setBirthday(new Date());
        user.setAddress("杭州市");
        UserDao userDao = new UserDaoImpl(sqlSessionFactory);
        userDao.updateUser(user);
    }

    @Test
    public void testDeleteUser() {
        UserDao userDao = new UserDaoImpl(sqlSessionFactory);
        userDao.deleteUser(10);
    }

}

  以上步驟,完成使用mybatis框架開發原始dao層,並對資料庫進行增刪改查操作。

  需要注意的是,上文提到的config資料夾和sqlmapper資料夾均為資原始檔夾(source folder),預設會載入該路徑下的檔案。