1. 程式人生 > >Mybatis --03.mybatis中的CRUD操作

Mybatis --03.mybatis中的CRUD操作

1、編寫UserDao介面

UserDao.java

package com.sswblog.dao;
import com.sswblog.domain.User;
import java.util.List;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 0:06 2018/11/5
 */
public interface UserDao {
    /**
     * 根據id查詢使用者
     * @param id
     * @return
     */
    public User findUserById(Long id);

    /**
     * 查詢所有使用者
     * @return
     */
    public List<User> findAllUsers();

    /**
     * 儲存使用者
     * @param user
     */
    public void save(User user);

    /**
     * 根據id刪除使用者
     * @param id
     */
    public void delete(Long id);

    /**
     * 更新使用者
     * @param user
     */
    public void update(User user);
}

2、編寫UserDao介面實現類

UserDaoImpl.java

package com.sswblog.dao.Impl;

import com.sswblog.dao.UserDao;
import com.sswblog.domain.User;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 0:06 2018/11/5
 */
public class UserDaoImpl implements UserDao {
    //dao層增刪除改查需要SqlSession
    private SqlSession sqlSession = null;

    //構造方法
    public UserDaoImpl(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public User findUserById(Long id) {
        User user = this.sqlSession.selectOne("UserDaoMapper.findUserById",id);
        this.sqlSession.close();
        return user;
    }

    @Override
    public List<User> findAllUsers() {
        List<User> users = this.sqlSession.selectList("UserDaoMapper.findAllUsers");
        this.sqlSession.close();
        return users;
    }

    @Override
    public void save(User user) {
        this.sqlSession.insert("UserDaoMapper.insertUser", user);
        //mybatis自動提交功能關了。所以要手動提交事務
        this.sqlSession.commit();
        this.sqlSession.close();

    }

    @Override
    public void delete(Long id) {
        this.sqlSession.delete("UserDaoMapper.deleteUser",id);
        this.sqlSession.commit();
        this.sqlSession.close();

    }

    @Override
    public void update(User user) {
        this.sqlSession.update("UserDaoMapper.updateUser",user);
        this.sqlSession.commit();
        this.sqlSession.close();

    }
}

3、CRUD標籤

對映檔案UserDaoMappers.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">
<!--對映檔案的作用:用來存放sql語句
    namespace:名稱空間
-->
<mapper namespace="UserDaoMapper">
    <!--通過id查詢使用者-->
    <select id="findUserById" resultType="User">
        select * from tb_user where id = #{id}
    </select>
    <!--查詢所有使用者-->
    <select id="findAllUsers" resultType="User">
        select * from tb_user;
    </select>
    <!--插入資料-->
    <!--id:唯一標識、在同一名稱空間下唯一-->
    <!--parameterType:引數的型別-->
    <!--useGeneratedKeys:開啟主鍵回寫-->
    <!--keyColumn:主鍵列名-->
    <!--keyProperty:主鍵對應的屬性名-->
    <!--內容:插入的sql-->
    <!--插入資料時、傳過來的引數是一個物件、#{**}中的名字必須與物件中屬性名一致-->
    <insert id="insertUser" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
        insert into tb_user(
          user_name,
          password,
          name,
          age,
          sex,
          birthday,
          created,
          updated
        )
        values(
          #{userName},
          #{password},
          #{name},
          #{age},
          #{sex},
          #{birthday},
          NOW(),
          NOW()
        )
    </insert>

    <!--更新操作:update-->
    <!--id:唯一標識、在同一名稱空間下唯一-->
    <!--parameterType:語句中佔位符、表示引數的型別-->
    <!--更新資料時、傳過來的引數是一個物件#{****}中名字必須與物件屬性名致-->
    <update id="updateUser">
         UPDATE tb_user set
           user_name = #{userName},
           password = #{password},
           name = #{name},
           age = #{age},
           sex = #{sex},
           birthday = #{birthday},
           updated = NOW()
        WHERE
           id = #{id}
    </update>

    <!--刪除delete-->
    <!--id:唯一標識-->
    <!--parameterType:佔位符、引數的型別-->
    <!---->
    <delete id="deleteUser">
        delete from tb_user where id = #{id}
    </delete>

</mapper>

mybatis核心配置檔案:

<?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="jdbc.properties"/>
    <!--開啟駝峰、讓實體類的屬性和資料庫中的鍵一一對映-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!--開啟別名-->
    <typeAliases>
        <!--<typeAlias type="com.sswblog.domain.User" alias="User" />-->
        <package name="com.sswblog.domain"/>
    </typeAliases>
    <!--
        environments標籤:用於配置多個環境(測試環境、生產環境)
            default屬性:預設環境的id
        environment標籤:配置一個具體的環境
            id屬性:一個具體環境的id
        transactionManager標籤:指定事務的型別
            type屬性:可以取的值有:JDBC|MANAGED
                JDBC:表示從資料來源獲取資料庫連線來提交或回滾事務
                MANAGED:表示把事務交給容器來管理,一般不用
        dataSource標籤:配置資料來源
            type屬性:指定資料來源型別,可以取的值有:UNPOOLED|POOLED|JNDI
                UNPOOLED:無連線池的資料來源,每次都重新獲取資料庫連線,使用完後關閉連線
                POOLED:帶連線池的資料來源
                JNDI:使用JNDI資料來源
    -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--指定驅動類名-->
                <property name="driver" value="${jdbc.driverClass}"/>
                <!-- 指定連線地址 -->
                <property name="url" value="${jdbc.url}"/>
                <!-- 指定使用者名稱 -->
                <property name="username" value="${jdbc.username}"/>
                <!-- 指定密碼 -->
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入對映檔案-->
    <mappers>
        <mapper resource="UserMappers.xml"></mapper>
        <mapper resource="UserDaoMappers.xml"></mapper>
    </mappers>

</configuration>

4、建立單元測試類

UserDaoImplTest.java

package com.sswblog.test;

import com.sswblog.dao.Impl.UserDaoImpl;
import com.sswblog.dao.UserDao;
import com.sswblog.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

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

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 15:05 2018/11/5
 */
public class UserDaoImplTest {
    private UserDao userDao = null;

    @Before
    public void setUp() throws Exception {
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        userDao = new UserDaoImpl(sqlSession);
    }

    @Test
    public void findUserById() {
        User user = userDao.findUserById(2L);
        System.out.println("user = " + user);
    }

    @Test
    public void findAllUsers() {
        List<User> list = userDao.findAllUsers();
        for (User user : list) {
            System.out.println("user = " + user);
        }
    }

    @Test
    public void save() {
        User user = new User();
        user.setUserName("小王");
        user.setPassword("111111");
        user.setName("庫裡");
        user.setSex(1);
        user.setAge(22);
        Date date = new Date();
        user.setBirthday(date);
        userDao.save(user);
        System.out.println("user = " + user);
    }

    @Test
    public void delete() {
        userDao.delete(3L);
    }

    @Test
    public void update() {
        User user = new User();
        user.setId(5L);
        user.setUserName("天天一");
        user.setPassword("666666");
        user.setName("庫裡2");
        user.setSex(1);
        user.setAge(22);
        Date date = new Date();
        user.setBirthday(date);
        userDao.update(user);
    }
}