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

作者:流楚丶格念 时间:2023-08-20 06:20:58 

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示例讲解注解开发中的单表操作

注意:

修改MyBatis的核心配置文件,我们使用了注解替代的映射文件,所以我们只需要加载使用了注解的Mapper接口即可

<mappers>
   <!--扫描使用注解的类-->
   <mapper class="com.yyl.mapper.UserMapper"></mapper>
</mappers>

或者指定扫描包含映射关系的接口所在的包也可以

<mappers>
   <!--扫描使用注解的类所在的包-->
   <package name="com.yyl.mapper"></package>
</mappers>

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

注解开发总结

注解可以简化开发操作,省略映射配置文件的编写。

常用注解

@Select(&ldquo;查询的 SQL 语句&rdquo;):执行查询操作注解
@Insert(&ldquo;查询的 SQL 语句&rdquo;):执行新增操作注解
@Update(&ldquo;查询的 SQL 语句&rdquo;):执行修改操作注解
@Delete(&ldquo;查询的 SQL 语句&rdquo;):执行删除操作注解 

配置映射关系

<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>

来源:https://yangyongli.blog.csdn.net/article/details/125588701

标签:Mybatis,单表操作,注解开发
0
投稿

猜你喜欢

  • 详解Maven profile配置管理及激活profile的几种方式

    2022-07-01 08:54:46
  • Spring Cloud之配置中心的搭建

    2023-04-02 21:19:49
  • C#借助OpenCvSharp读取摄像头并显示的实现示例

    2022-12-22 05:49:51
  • Java中的static关键字深入理解

    2022-02-01 12:59:40
  • java实现简单单链表

    2023-10-30 09:45:46
  • 因Spring AOP导致@Autowired依赖注入失败的解决方法

    2022-10-24 19:44:11
  • android之listview悬浮topBar效果

    2022-12-24 23:29:58
  • 基于Java接口回调详解

    2023-11-09 00:03:11
  • Android编程设计模式之迭代器模式详解

    2023-06-07 01:25:42
  • Android自定义顶部导航栏控件实例代码

    2022-02-11 13:43:16
  • Java BIO,NIO,AIO总结

    2022-02-07 01:48:28
  • SpringBoot服务开启后通过端口访问无反应的解决

    2022-12-11 03:57:17
  • c#中var关键字用法浅谈

    2022-03-14 00:21:51
  • Java实现几种常见排序算法代码

    2022-10-10 20:42:19
  • Android基于OpenCV实现QR二维码检测

    2021-12-13 07:56:39
  • 浅析java修饰符访问权限(动力节点Java学院整理)

    2023-07-13 18:07:34
  • c# 用Dictionary实现日志数据批量插入

    2022-05-29 02:01:45
  • idea生成类注释和方法注释的正确方法(推荐)

    2022-09-11 03:45:14
  • Android中Listview下拉刷新和上拉加载更多的多种实现方案

    2022-11-19 17:00:43
  • Android App中使用Gallery制作幻灯片播放效果

    2022-04-03 21:53:37
  • asp之家 软件编程 m.aspxhome.com