Mybatis示例講解註解開發中的單表操作

Mybatis註解開發單表操作

MyBatis的常用註解

Mybatis也可以使用註解開發方式,這樣我們就可以減少編寫Mapper映射文件瞭。我們先圍繞一些基本的CRUD來學習,再學習復雜映射多表操作。

註解 說明
@Insert 實現新增
@Update 實現更新
@Delete 實現刪除
@Select 實現查詢
@Result 實現結果集封裝
@Results 可以與@Result 一起使用,封裝多個結果集
@One 實現一對一結果集封裝
@Many 實現一對多結果集封

MyBatis的增刪改查

我們完成簡單的student表的增刪改查的操作

步驟一:創建mapper接口

public interface StudentMapper {
    //查詢全部
    @Select("SELECT * FROM student")
    public abstract List<Student> selectAll();
    //新增操作
    @Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
    public abstract Integer insert(Student stu);
    //修改操作
    @Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
    public abstract Integer update(Student stu);
    //刪除操作
    @Delete("DELETE FROM student WHERE id=#{id}")
    public abstract Integer delete(Integer id);
}

步驟二:測試類

public class Test01 {
    @Test
    public void selectAll() throws Exception{
        //1.加載核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //2.獲取SqlSession工廠對象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通過工廠對象獲取SqlSession對象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.獲取StudentMapper接口的實現類對象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.調用實現類對象中的方法,接收結果
        List<Student> list = mapper.selectAll();
        //6.處理結果
        for (Student student : list) {
            System.out.println(student);
        }
        //7.釋放資源
        sqlSession.close();
        is.close();
    }
    @Test
    public void insert() throws Exception{
        //1.加載核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //2.獲取SqlSession工廠對象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通過工廠對象獲取SqlSession對象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.獲取StudentMapper接口的實現類對象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.調用實現類對象中的方法,接收結果
        Student stu = new Student(4,"趙六",26);
        Integer result = mapper.insert(stu);
        //6.處理結果
        System.out.println(result);
        //7.釋放資源
        sqlSession.close();
        is.close();
    }
    @Test
    public void update() throws Exception{
        //1.加載核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //2.獲取SqlSession工廠對象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通過工廠對象獲取SqlSession對象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.獲取StudentMapper接口的實現類對象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.調用實現類對象中的方法,接收結果
        Student stu = new Student(4,"趙六",36);
        Integer result = mapper.update(stu);
        //6.處理結果
        System.out.println(result);
        //7.釋放資源
        sqlSession.close();
        is.close();
    }
    @Test
    public void delete() throws Exception{
        //1.加載核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //2.獲取SqlSession工廠對象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通過工廠對象獲取SqlSession對象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.獲取StudentMapper接口的實現類對象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.調用實現類對象中的方法,接收結果
        Integer result = mapper.delete(4);
        //6.處理結果
        System.out.println(result);
        //7.釋放資源
        sqlSession.close();
        is.close();
    }
}

例如運行test1結果如下:

註意:

修改MyBatis的核心配置文件,我們使用瞭註解替代的映射文件,所以我們隻需要加載使用瞭註解的Mapper接口即可

<mappers>
    <!--掃描使用註解的類-->
    <mapper class="com.yyl.mapper.UserMapper"></mapper>
</mappers>

​ 或者指定掃描包含映射關系的接口所在的包也可以

<mappers>
    <!--掃描使用註解的類所在的包-->
    <package name="com.yyl.mapper"></package>
</mappers>

註解開發總結

註解可以簡化開發操作,省略映射配置文件的編寫。

常用註解

@Select(“查詢的 SQL 語句”):執行查詢操作註解
@Insert(“查詢的 SQL 語句”):執行新增操作註解
@Update(“查詢的 SQL 語句”):執行修改操作註解
@Delete(“查詢的 SQL 語句”):執行刪除操作註解 

配置映射關系

<mappers> 
    <package name="接口所在包"/> 
</mappers>    

練習項目代碼

bean

package com.yyl.bean;
public class Student {
    private Integer id;
    private String name;
    private Integer age;
    public Student() {
    }
    public Student(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

mapper.class

package com.yyl.mapper;
import com.yyl.bean.Student;
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 StudentMapper {
    //查詢全部
    @Select("SELECT * FROM student")
    public abstract List<Student> selectAll();
    //新增操作
    @Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
    public abstract Integer insert(Student stu);
    //修改操作
    @Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
    public abstract Integer update(Student stu);
    //刪除操作
    @Delete("DELETE FROM student WHERE id=#{id}")
    public abstract Integer delete(Integer id);
}

test

package com.yyl.test;
import com.yyl.bean.Student;
import com.yyl.mapper.StudentMapper;
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.Test;
import java.io.InputStream;
import java.util.List;
public class Test01 {
    @Test
    public void selectAll() throws Exception{
        //1.加載核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //2.獲取SqlSession工廠對象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通過工廠對象獲取SqlSession對象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.獲取StudentMapper接口的實現類對象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.調用實現類對象中的方法,接收結果
        List<Student> list = mapper.selectAll();
        //6.處理結果
        for (Student student : list) {
            System.out.println(student);
        }
        //7.釋放資源
        sqlSession.close();
        is.close();
    }
    @Test
    public void insert() throws Exception{
        //1.加載核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //2.獲取SqlSession工廠對象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通過工廠對象獲取SqlSession對象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.獲取StudentMapper接口的實現類對象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.調用實現類對象中的方法,接收結果
        Student stu = new Student(4,"趙六",26);
        Integer result = mapper.insert(stu);
        //6.處理結果
        System.out.println(result);
        //7.釋放資源
        sqlSession.close();
        is.close();
    }
    @Test
    public void update() throws Exception{
        //1.加載核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //2.獲取SqlSession工廠對象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通過工廠對象獲取SqlSession對象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.獲取StudentMapper接口的實現類對象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.調用實現類對象中的方法,接收結果
        Student stu = new Student(4,"趙六",36);
        Integer result = mapper.update(stu);
        //6.處理結果
        System.out.println(result);
        //7.釋放資源
        sqlSession.close();
        is.close();
    }
    @Test
    public void delete() throws Exception{
        //1.加載核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //2.獲取SqlSession工廠對象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通過工廠對象獲取SqlSession對象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.獲取StudentMapper接口的實現類對象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.調用實現類對象中的方法,接收結果
        Integer result = mapper.delete(4);
        //6.處理結果
        System.out.println(result);
        //7.釋放資源
        sqlSession.close();
        is.close();
    }
}

xml

<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD約束-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration 核心根標簽-->
<configuration>
    <!--引入數據庫連接的配置文件-->
    <properties resource="jdbc.properties"/>
    <!--配置LOG4J-->
    <settings>
        <setting name="logImpl" value="log4j"/>
    </settings>
    <!--起別名-->
    <typeAliases>
        <package name="com.yyl.bean"/>
    </typeAliases>
    <!--environments配置數據庫環境,環境可以有多個。default屬性指定使用的是哪個-->
    <environments default="mysql">
        <!--environment配置數據庫環境  id屬性唯一標識-->
        <environment id="mysql">
            <!-- transactionManager事務管理。  type屬性,采用JDBC默認的事務-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- dataSource數據源信息   type屬性 連接池-->
            <dataSource type="POOLED">
                <!-- property獲取數據庫連接的配置信息 -->
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
    <!--配置映射關系-->
    <mappers>
        <package name="com.yyl.mapper"/>
    </mappers>
</configuration>

到此這篇關於Mybatis示例講解註解開發中的單表操作的文章就介紹到這瞭,更多相關Mybatis單表操作內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: