MyBatis 的 配置檔案開發方式 和 註解開發方式(對資料庫進行增刪改查)

於小猿發表於2020-11-03

程式碼較多,請耐心看完,一定能學會!!!

首先不使用註解方式把環境配置好:

1、目錄結構:

2、根據資料庫中的 user 表,寫一個 user 的實體類 (cn.henu.domain.User.java)

package cn.henu.domain;
import java.util.Date;
public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday=" + birthday +
                '}';
    }

    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 getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

3、寫一個持久層檔案,裡面定義一些運算元據庫的方法(cn.henu.mapper.UserMapper.java)

package cn.henu.mapper;

import cn.henu.domain.User;
import java.util.List;

public interface UserMapper {
    //插入操作
    public void save(User user);
    //更新操作
    public void update(User user);
    //刪除操作
    public void delete(int id);
    //根據id查詢
    public User findById(int id);
    //查詢全部
    public List<User> findAll();
}

4、寫一個對映檔案,裡面寫SQL語句(cn/henu/mapper/UserMapper.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="cn.henu.mapper.UserMapper">

    <insert id="save" parameterType="user">
        insert into user values (#{id},#{username},#{password},#{birthday})
    </insert>

    <update id="update" parameterType="user">
        update user set username = #{username},password = #{password} where id = #{id}
    </update>

    <delete id="delete" parameterType="int">
        delete from user where id = #{id}
    </delete>

    <select id="findById" parameterType="int" resultType="user">
        select * from user where id = #{id}
    </select>

    <select id="findAll" resultType="user">
        select * from user
    </select>
</mapper>

5、編寫 Spring 核心配置檔案(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標籤載入外部的properties檔案-->
    <properties resource="jdbc.properties"></properties>
    <!--自定義別名-->
    <typeAliases>
        <typeAlias type="cn.henu.domain.User" alias="user"></typeAlias>
    </typeAliases>

    <!--配置資料來源環境-->
    <environments default="developement">
        <environment id="developement">
            <transactionManager type="JDBC"></transactionManager>
            <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>
        <mapper resource="cn/henu/mapper/UserMapper.xml"></mapper>
    </mappers>

</configuration>

6、編寫一個測試類,來測試這些運算元據庫的方法(cn.henu.test.MybatisTest.java)

package cn.henu.test;

import cn.henu.domain.User;
import cn.henu.mapper.UserMapper;
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.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest {
    private UserMapper mapper;
    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        mapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test//測試插入
    public void testSave(){
        User user = new User();
        user.setUsername("tom");
        user.setPassword("abc");
        mapper.save(user);
    }

    @Test//測試更新
    public void testUpdate(){
        User user = new User();
        user.setId(18);
        user.setUsername("lucy");
        user.setPassword("123");
        mapper.update(user);
    }

    @Test//測試刪除
    public void testDelete(){
        mapper.delete(18);
    }

    @Test//測試根據id查詢使用者
    public void testFindById(){
        User user = mapper.findById(2);
        System.out.println(user);
    }

    @Test//測試查詢全部使用者
    public void testFindAll(){
        List<User> all = mapper.findAll();
        for (User user : all) {
            System.out.println(user);
        }
    }
}

7、執行第6步的每一個Test方法,並且檢視資料庫中相應的表,都能正確執行,而且能夠成功運算元據庫。下面在此基礎上介紹註解方式


1、將對映檔案 UserMapper.xml 中的SQL語句全部使用註解的形式寫在 UserMapper.java 中(cn.henu.mapper.UserMapper.java)

package cn.henu.mapper;

import cn.henu.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface UserMapper {
    //插入操作
    @Insert("insert into user values (#{id},#{username},#{password},#{birthday})")
    public void save(User user);
    //更新操作
    @Update("update user set username = #{username},password = #{password} where id = #{id}")
    public void update(User user);
    //刪除操作
    @Delete("delete from user where id = #{id}")
    public void delete(int id);
    //根據id查詢
    @Select("select * from user where id = #{id}")
    public User findById(int id);
    //查詢全部
    @Select("select * from user")
    public List<User> findAll();
}

2、修改 Spring 核心配置檔案(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標籤載入外部的properties檔案-->
    <properties resource="jdbc.properties"></properties>
    <!--自定義別名-->
    <typeAliases>
        <typeAlias type="cn.henu.domain.User" alias="user"></typeAlias>
    </typeAliases>

    <!--配置資料來源環境-->
    <environments default="developement">
        <environment id="developement">
            <transactionManager type="JDBC"></transactionManager>
            <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>
        <!--指定介面所在的包-->
        <package name="cn.henu.mapper"/>
    </mappers>

</configuration>

3、刪除對映檔案 UserMapper.xml(UserMapper.xml 已經沒用了)

4、執行上面第6步的測試類,依然能夠正確執行,並且能夠成功運算元據庫

相關文章