MyBatis的注解式开发

MyBatis的注解式开发

  • 一、准备开发环境
    • 1.添加依赖
    • 2.jdbc.properties
    • 3.mybatis-config.xml
    • 4.Article实体类
    • 5.SqlSessionUtil工具类
  • 二、Insert
  • 三、Delete
  • 四、Update
  • 五、Select

  • mybatis 中也提供了注解式开发⽅式,采⽤注解可以减少 Sql 映射⽂件的配置。
  • 使⽤注解式开发的话,sql语句是写在java程序中的,这种⽅式也会给sql语句的维护带来成本。
    • 官⽅是这么说的:使⽤注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂⼀点的语句,Java 注解不仅⼒不从⼼,还会让你本就复杂的 SQL 语句更加混乱不堪。 因此,如果你需要做⼀些很复杂的操作,最好⽤ XML 来映射语句。
  • 总结:一般对单表的 CRUD 可以采用注解的方式开发。

一、准备开发环境

1.添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>coml.gdb</groupId><artifactId>mybatis-annotation</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.14</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency></dependencies>
</project>

2.jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/自己的数据库名字
jdbc.username=用户名
jdbc.password=密码

3.mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><properties resource="jdbc.properties"></properties><settings><setting name="logImpl" value="STDOUT_LOGGING"/></settings><environments default="development"><environment id="development"><transactionManager type="JDBC"/><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><!--sql映射⽂件创建好之后,需要将该⽂件路径配置到这⾥--><!-- 注意:这里不是使用的mapper配置项,而是使用的package --><package name="com.gdb.annotation.mapper"/></mappers></configuration>

4.Article实体类

package com.gdb.annotation.pojo;import java.time.LocalDateTime;public class Article {private Integer id;private Integer userId;private String summary;private String title;private Integer readCount;private LocalDateTime createTime;private LocalDateTime updateTime;@Overridepublic String toString() {return "Article{" +"id=" + id +", userId=" + userId +", summary='" + summary + '\'' +", title='" + title + '\'' +", readCount=" + readCount +", createTime=" + createTime +", updateTime=" + updateTime +'}';}public Article() {}public Article(Integer id, Integer userId, String summary, String title, Integer readCount, LocalDateTime createTime, LocalDateTime updateTime) {this.id = id;this.userId = userId;this.summary = summary;this.title = title;this.readCount = readCount;this.createTime = createTime;this.updateTime = updateTime;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public Integer getUserId() {return userId;}public void setUserId(Integer userId) {this.userId = userId;}public String getSummary() {return summary;}public void setSummary(String summary) {this.summary = summary;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public Integer getReadCount() {return readCount;}public void setReadCount(Integer readCount) {this.readCount = readCount;}public LocalDateTime getCreateTime() {return createTime;}public void setCreateTime(LocalDateTime createTime) {this.createTime = createTime;}public LocalDateTime getUpdateTime() {return updateTime;}public void setUpdateTime(LocalDateTime updateTime) {this.updateTime = updateTime;}
}

5.SqlSessionUtil工具类

package com.gdb.annotation.utils;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class SqlSessionUtil {private static SqlSessionFactory sqlSessionFactory;/*** 类加载时初始化sqlSessionFactory对象*/static {try {SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));} catch (Exception e) {e.printStackTrace();}}/*** 每调⽤⼀次openSession()可获取⼀个新的会话*/public static SqlSession openSession() {return sqlSessionFactory.openSession();}
}

二、Insert

  • ArticleMapper 接口
package com.gdb.annotation.mapper;import com.gdb.annotation.pojo.Article;
import org.apache.ibatis.annotations.Insert;public interface ArticleMapper {@Insert("insert into article values (null, #{userId}, #{title}, #{summary}, #{readCount}, #{createTime}, #{updateTime})")int insert(Article article);}
  • Annotation.InsertAnnotationtest
package com.gdb.annotationTest;import com.gdb.annotation.mapper.ArticleMapper;
import com.gdb.annotation.pojo.Article;
import com.gdb.annotation.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.time.LocalDateTime;public class Annotation {@Testpublic void insertAnnotationTest(){SqlSession sqlSession = MybatisUtils.openSession();ArticleMapper mapper = sqlSession.getMapper(ArticleMapper.class);Article article = new Article(null, 12346, "springboot 配置文件", "外部化配置文件", 12346, LocalDateTime.now(), LocalDateTime.now());int count = mapper.insert(article);System.out.println("插入的记录条数 ===> " + count);sqlSession.commit();sqlSession.close();}
}

三、Delete

  • ArticleMapper 接口
@Delete("delete from article where id = #{id}")
int delete(int id);
  • Annotation.deleteAnnotationTest
@Test
public void deleteAnnotationTest(){SqlSession sqlSession = MybatisUtils.openSession();ArticleMapper mapper = sqlSession.getMapper(ArticleMapper.class);int count = mapper.delete(13);System.out.println("删除的记录条数 ===> " + count);sqlSession.commit();sqlSession.close();}

四、Update

  • ArticleMapper 接口
@Update("update article set user_id=#{userId}, title=#{title} where id=#{id}")
int update(Article article);
  • Annotation.updateAnnotationTest
@Test
public void updateAnnotationTest(){SqlSession sqlSession = MybatisUtils.openSession();ArticleMapper mapper = sqlSession.getMapper(ArticleMapper.class);Article article = new Article(19, 12346, "springboot 配置文件", "外部化配置文件", 12346, LocalDateTime.now(), LocalDateTime.now());int count = mapper.update(article);System.out.println("插入的记录条数 ===> " + count);sqlSession.commit();sqlSession.close();
}

五、Select

  • ArticleMapper 接口
@Select("select * from Article where id = #{id}")
@Results({@Result(property = "userId", column = "user_id"),@Result(property = "readCount", column = "read_count"),@Result(property = "createTime", column = "create_time"),@Result(property = "updateTime", column = "update_time")
})
Article selectById(int id);
  • Annotation.seleteAnnotationTest
@Test
public void selectAnnotationTest(){SqlSession sqlSession = MybatisUtils.openSession();ArticleMapper mapper = sqlSession.getMapper(ArticleMapper.class);Article article = mapper.selectById(1);System.out.println(article);sqlSession.commit();sqlSession.close();
}
  • 注意:如果不想使用 @Results 注解的话可以在mybatis-config.xml 配置文件中添加如下配置。
    <settings><setting name="mapUnderscoreToCamelCase" value="true"/></settings>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/694815.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

设计模式浅析(六) ·命令模式

设计模式浅析(六) 命令模式 日常叨逼叨 java设计模式浅析&#xff0c;如果觉得对你有帮助&#xff0c;记得一键三连&#xff0c;谢谢各位观众老爷&#x1f601;&#x1f601; 命令模式 概念 命令模式&#xff08;Command Pattern&#xff09;是一种行为设计模式&#xff0c…

YOLOv5代码解读[02] models/yolov5l.yaml文件解析

文章目录 YOLOv5代码解读[02] models/yolov5l.yaml文件解析yolov5l.yaml文件检测头1--->耦合头检测头2--->解耦头检测头3--->ASFF检测头Model类解析parse_model函数 YOLOv5代码解读[02] models/yolov5l.yaml文件解析 yolov5l.yaml文件 # YOLOv5 &#x1f680; by Ult…

FPGA SERDESE2 (SDR收发仿真)

高速 Serdes 环路测试 高速串行通信优势非常巨大,只需要很少的IO引脚就可以实现高速通信,这也是当今FPGA高速接口的核心 技术。比如XILINX的7代FPGA,GTX可以达到10.3125Gbps,ultrascale FPGA的GTH可以达到16Gbps。目前国产FPGA还难以达到这么高的接口速度。 高速串行通信经…

社区分享|中华保险基于MeterSphere开展接口自动化测试

中华联合保险集团股份有限公司&#xff08;以下简称为“中华保险”&#xff09;始创于1986年&#xff0c;是全国唯一一家以“中华”冠名的国有控股保险公司。截至2022年12月底&#xff0c;中华保险总资产为1006.06亿元&#xff0c;在全国拥有超过2900个营业网点&#xff0c;员工…

Servlet中的请求与响应

Request和Response 1.Request和Response的概述2.Request对象2.1 Request继承体系2.2 Request获取请求数据2.3 解决post请求乱码问题 *2.4 Request请求转发(-&#xff0c;*)2.5 request的生命周期 3.HTTP响应详解(理解)1.使用抓包查看响应报文协议内容2.HTTP响应报文协议介绍 4.…

汇编英文全称

mov move mvn Mov Negative ldr LoaD Register str Store Register lsl Logic Shift Left lsr Logic Shift Right asr Arithmetic Shift Right 算数右移 ror Rotate right 循环右移…

人工智能讲师AI讲师大模型讲师叶梓介绍及大语言模型技术原理与实践提纲

叶梓&#xff0c;上海交通大学计算机专业博士毕业&#xff0c;高级工程师。主研方向&#xff1a;数据挖掘、机器学习、人工智能。历任国内知名上市IT企业的AI技术总监、资深技术专家&#xff0c;市级行业大数据平台技术负责人。 长期负责城市信息化智能平台的建设工作&#xff…

angular-引用本地json文件

angular-引用json文件&#xff0c;本地模拟数据时使用 在assets目录下存放json文件 大佬们的说法是&#xff1a;angular配置限定了资源文件的所在地&#xff08;就是assets的路径&#xff09;&#xff0c;放在其他文件夹中&#xff0c;angular在编译过程中会忽略&#xff0c;会…

云计算的两地三中心和灾备介绍

两地三中心是指在不同的地理位置建立两个数据中心和一个灾备中心&#xff0c;其中一个数据中心为主数据中心&#xff0c;另一个数据中心为备用数据中心&#xff0c;灾备中心则用于备份数据和在主数据中心或备用数据中心发生故障或灾难时提供应急支持。 异地灾备则是指在不同的地…

Docker之查看并获取最新Ubuntu镜像(十)

简介&#xff1a; CSDN博客专家&#xff0c;专注Android/Linux系统&#xff0c;分享多mic语音方案、音视频、编解码等技术&#xff0c;与大家一起成长&#xff01; 优质专栏&#xff1a;Audio工程师进阶系列【原创干货持续更新中……】&#x1f680; 优质专栏&#xff1a;多媒…

基于springboot+vue的教学资源库系统(前后端分离)

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、阿里云专家博主、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战&#xff0c;欢迎高校老师\讲师\同行交流合作 ​主要内容&#xff1a;毕业设计(Javaweb项目|小程序|Pyt…

Nginx配置组成与性能调优

目录 一、Nginx配置介绍 1. 模块组成 2. 图示 3. 相关框架 二. 配置调优 1. 全局配置 1.1 关闭版本和修改版本 1.2 修改启动的进程数 1.3 cpu与work进程绑定 1.4 pid路径 1.5 nginx进程的优先级&#xff08;work进程的优先级&#xff09; 1.6 调试work进程打开的文…

利用System.Web.HttpRuntime.Cache制作缓存工具类

用到的依赖介绍 当谈到 ASP.NET 中的缓存管理时&#xff0c;常涉及到以下三个类&#xff1a;CacheDependency、HttpRuntime.Cache 和 System.Web.Caching。 CacheDependency&#xff08;缓存依赖项&#xff09;&#xff1a; CacheDependency 类用于指定一个或多个文件或目录作…

问题:Spark SQL 读不到 Flink 写入 Hudi 表的新数据,打开新 Session 才可见

博主历时三年精心创作的《大数据平台架构与原型实现&#xff1a;数据中台建设实战》一书现已由知名IT图书品牌电子工业出版社博文视点出版发行&#xff0c;点击《重磅推荐&#xff1a;建大数据平台太难了&#xff01;给我发个工程原型吧&#xff01;》了解图书详情&#xff0c;…

Predis Multi-Zone

A Data Flow Framework with High Throughput and Low Latency for Permissioned Blockchains 联盟链的吞吐瓶颈由共识层和网络层的数据分发过程共同决定。 Predis 协议利用了共识节点的空闲带宽&#xff0c;提前分发区块中的内容即bundle&#xff0c;减少了共识区块中的内容&…

在vue3中使用canvas实现雨滴效果

在vue3中使用canvas实现雨滴效果 这是封装的一个组件DotAndRain&#xff08; &#xff09; <script setup> import { ref, onMounted } from "vue"; import { onUnmounted } from "vue";let animationFrameId null;const el ref(null); let canv…

5 原型模式 Prototype

1.模式定义: 指原型实例指定创建对象的种类&#xff0c;并且通过拷贝这些原型创建新的对象 2.应用场景&#xff1a; 当代码不应该依赖于需要复制的对象的具体类时&#xff0c;请使用Prototype模式。 Spring源码中的应用 org.springframework.beans.factory.support.AbstractB…

QT 如何让多语言翻译变得简单,提高效率?

一.QT多语言如何翻译的? 在QT的多语言翻译过程中,分为两个步骤:第一步生成ts文件,第二步将ts文件翻译为qm文件。如果我们在需要多语言的情况下,qml经常使用qstr或者qwidget中使用tr等等,遍布许多个文件夹,在需要更新新的翻译时会很麻烦。整个工程收索并修改,效率十分低…

vue3 #ref #reactive

一、ref 函数将简单类型的数据包装为响应式数据 import { ref } from vue const count ref(10) 一、reactive函数将复杂类型的数据包装为响应式数据 import { reactive} from vue const obj reactive({ name : zs&#xff0c; age : 18 })

蓝桥杯嵌入式第12届真题(完成) STM32G431

蓝桥杯嵌入式第12届真题(完成) STM32G431 题目 程序 main.c /* USER CODE BEGIN Header */ /********************************************************************************* file : main.c* brief : Main program body**************************…