Mybatis示例讲解注解开发中的单表操作

 更新时间:2022年07月06日 09:17:00   作者:流楚丶格念  
这篇文章主要介绍了使用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单表操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • MyBatis-Plus实现分页的方法使用详解

    MyBatis-Plus实现分页的方法使用详解

    这篇文章主要为大家介绍了MyBatis-Plus的分页的方法使用,包括:不传参数时的默认结果、查询不存在的数据、手动包装page和自定义SQL,需要的可以参考一下
    2022-03-03
  • mybatis中的缓存机制

    mybatis中的缓存机制

    这篇文章主要介绍了mybatis中的缓存机制用法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • SpringCloud对服务内某个client进行单独配置的操作步骤

    SpringCloud对服务内某个client进行单独配置的操作步骤

    我们的微服务项目用的是springCloud,某个微服务接口因为数据处理量大,出现了接口超时的情况,我们需要单独修改这一个feignClient的超时时间,所以本文介绍了SpringCloud对服务内某个client进行单独配置的操作步骤,需要的朋友可以参考下
    2023-10-10
  • 浅谈SpringBoot2.4 配置文件加载机制大变化

    浅谈SpringBoot2.4 配置文件加载机制大变化

    这篇文章主要介绍了浅谈SpringBoot2.4 配置文件加载机制大变化,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-08-08
  • Spring Bean生命周期之Bean元信息的配置与解析阶段详解

    Spring Bean生命周期之Bean元信息的配置与解析阶段详解

    这篇文章主要为大家详细介绍了Spring Bean生命周期之Bean元信息的配置与解析阶段,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-03-03
  • java实现屏蔽词功能

    java实现屏蔽词功能

    这篇文章主要介绍了java实现屏蔽词功能,类似贴吧里面屏蔽各种用户的发帖内容,感兴趣的小伙伴们可以参考一下
    2015-12-12
  • java线程池ThreadPoolExecutor类使用小结

    java线程池ThreadPoolExecutor类使用小结

    这篇文章主要介绍了java线程池ThreadPoolExecutor类使用,本文主要对ThreadPoolExecutor的使用方法进行一个详细的概述,示例代码介绍了ThreadPoolExecutor的构造函数的相关知识,感兴趣的朋友一起看看吧
    2022-03-03
  • Java Swing实现扫雷源码

    Java Swing实现扫雷源码

    这篇文章主要为大家详细介绍了Java Swing实现扫雷源码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-06-06
  • Maven配置文件修改及导入第三方jar包的实现

    Maven配置文件修改及导入第三方jar包的实现

    本文主要介绍了Maven配置文件修改及导入第三方jar包的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-08-08
  • SpringBoot配置Redis自定义过期时间操作

    SpringBoot配置Redis自定义过期时间操作

    这篇文章主要介绍了SpringBoot配置Redis自定义过期时间操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07

最新评论