当前位置: 首页 > news >正文

MyBatis的基础操作

目录

一.什么是MyBatis?

二.使用MyBatis的准备工作

1.引入依赖:

2.配置数据库连接字符串(建立MaBatis和MySQL的连接)

3.在model包中建立数据库对应的实体类UserInfo

三.通过@注解的方式实现MyBatis的开发

1.插入语句(Insert)

2.删除语句(Delete)

3.更新语句(Update)

4.查询语句(Select) 

1.起别名:

2.结果映射:

3.开启驼峰命名:

四.通过xml的方式实现MyBatis的开发

1.前提准备:

1)添加关于xml的配置(yml)

2)在resources文件夹中添加xml文件,在文件写入固定格式

3)接着就可以在里写数据库语句了

2.插入语句(Insert)

3.删除语句(Delete)

4.更新语句(Update)

5.查询语句(Select)


一.什么是MyBatis?

MyBatis是一个开源的持久层框架,它提供了一种优雅的方式来管理数据库访问代码。MyBatis通过将SQL语句映射到Java方法,使得在Java应用程序中执行数据库操作变得更加简单和直观。

MyBatis的核心思想是将SQL语句与Java方法和参数进行绑定,这样可以避免传统的JDBC编程中的大量样板代码。开发人员可以使用XML或注解来定义SQL映射,将SQL语句保存在外部文件中,并将其与Java接口或类进行绑定。


二.使用MyBatis的准备工作

1.引入依赖:

        <dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.1</version></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency>

2.配置数据库连接字符串(建立MaBatis和MySQL的连接)

spring:datasource:url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=falseusername: rootpassword: rootdriver-class-name: com.mysql.cj.jdbc.Driver
mybatis:configuration: # 配置打印 MyBatis⽇志map-underscore-to-camel-case: true #配置驼峰⾃动转换log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3.在model包中建立数据库对应的实体类UserInfo

public class UserInfo {private Integer id;private String username;private String password;private Integer age;private Integer gender;private String phone;private Integer deleteFlag;private Date createTime;private Date updateTime;
}

前提工作做完后,就可以实现数据库操作了


三.通过@注解的方式实现MyBatis的开发

1.插入语句(Insert)

使用@Insert("")注解,并在("")中实现插入语句

示例:

@Insert("insert into userinfo (username, password, age, gender, phone) " +"values (#{userInfo.username},#{userInfo.password},#{userInfo.age}," +"#{userInfo.gender},#{userInfo.phone})")Integer insertUserInfo(UserInfo userInfo);//在上述代码中实现了插入一个userInfo对象的信息到数据库中userinfo的表中
//userInfo的属性不能直接写到sql语句中,而是通过#{userInfo.属性字段}来自动查找userInfo的属性并填入sql语句中

同时可以搭配@Param注解使用,为方法中的参数指定名称

@Insert("insert into userinfo (username, password, age, gender, phone) " +"values (#{user.username}, #{user.password}, #{user.age}," +"#{user.gender}, #{user.phone})")Integer insertUserInfo2(@Param("user") UserInfo userInfo);//将userInfo识别成user使用

当传入参数有多个时,会按顺序填入各属性,而使用@Param就可以更自由的使用参数,同时可以提高代码的清晰度和可读性

Insert 语句默认返回的是受影响的行数,如果想要拿到⾃增id, 需要在方法上添加⼀个@Options注解

    @Options(useGeneratedKeys = true, keyProperty = "id")@Insert("insert into userinfo (username, password, age, gender, phone) " +"values (#{user.username}, #{user.password}, #{user.age}," +"#{user.gender}, #{user.phone})")Integer insertUserInfo2(@Param("user") UserInfo userInfo);
  • useGeneratedKeys = true表示告诉 MyBatis 在执行插入操作后要生成主键。当这个参数设置为 true 时,MyBatis 会通知数据库生成主键,并将生成的主键值返回给应用程序。

  • keyProperty = "id"表示指定将生成的主键值设置到对象的哪个属性上。在这里,keyProperty 指定了要将生成的主键值设置到对象的 id 属性上。

示例:

UserInfo newUser = new UserInfo();
newUser.setUsername("testUser");
newUser.setPassword("123456");
newUser.setAge(25);
newUser.setGender("male");
newUser.setPhone("123456789");Integer result = insertUserInfo2(newUser);System.out.println("插入成功,生成的主键值为:" + newUser.getId());//返回的主键值自动设置到newUser的id属性上了
//⽅法返回值result依然是受影响的⾏数

2.删除语句(Delete)

使用@Delete("")注解,并在("")中实现删除语句

示例:

  @Delete("delete from userinfo where id = #{id}")void delete(Integer id);//通过id删除某个用户

 同样可以使用@Param注解 

3.更新语句(Update)

使用@Update("")注解,并在("")中实现更新语句

示例:

@Update("update userinfo set username=#{username} where id=#{id}")void update(UserInfo userInfo);//通过id更新用户的姓名

4.查询语句(Select) 

使用@Select("")注解,并在("")中实现查询语句

示例:

    @Select("select id, username, password, age, gender, phone, delete_flag, " +"create_time, update_time from userinfo")List<UserInfo> queryAllUser();

MyBatis会自动将查询出的表的数据按照字段名依次放入List<UserInfo> 对象中

但是,如果表的字段名类的属性不一致时,就无法正常赋值了,例如表中的create_time字段类的createTime属性

解决办法:

1.起别名:
@Select("select id, username, `password`, age, gender, phone, delete_flag " +"as deleteFlag, create_time as createTime, update_time as updateTime " +"from userinfo")public List<UserInfo> queryAllUser2();//查询语句中 as 加上想改成的名字
2.结果映射:
@Select("select id, username, `password`, age, gender, phone, delete_flag, 
create_time, update_time from userinfo")
@Results({@Result(column = "delete_flag",property = "deleteFlag"),@Result(column = "create_time",property = "createTime"),@Result(column = "update_time",property = "updateTime")
})
List<UserInfo> queryAllUser();
3.开启驼峰命名:

在yml配置中加上:

mybatis:configuration:map-underscore-to-camel-case: true #配置驼峰⾃动转换

到此关于注解实现MyBatis的方式就结束了~


四.通过xml的方式实现MyBatis的开发

1.前提准备:

1)添加关于xml的配置(yml)
mybatis:mapper-locations: classpath:mapper/**Mapper.xml
2)在resources文件夹中添加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="com.example.demo.mapper.UserInfoMapper">//写MySQL语句
</mapper>
3)接着就可以在<mapper></mapper>里写数据库语句了

2.插入语句(Insert)

使用<insert>标签实现插入语句

<mapper namespace="com.example.demo.mapper.UserInfoMapper"><insert id="insertUser">insert into userinfo (username, password, age, gender, phone) values (#{username}, #{password}, #{age},#{gender},#{phone})</insert></mapper>

sql语句基本没有变化,只是放入了<insert>标签以及用id指定了mapper中要实现的接口的方法名

如果要返回自增 id,则需要设置useGeneratedKeys 和keyProperty属性

<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">insert into userinfo (username, `password`, age, gender, phone) values(#{userinfo.username},#{userinfo.password},#{userinfo.age},#
{userinfo.gender},#{userinfo.phone})
</insert>

3.删除语句(Delete)

使用<delete>标签实现删除语句

<delete id="deleteUser">delete from userinfo where id = #{id}
</delete>

4.更新语句(Update)

使用<update>标签实现更新语句

<update id="updateUser">update userinfo set username=#{username} where id=#{id}
</update>

5.查询语句(Select)

使用<select>标签实现查询语句

<select id="queryAllUser" resultType="com.example.demo.model.UserInfo">select id, username,`password`, age, gender, phone, delete_flag,create_time, update_time from userinfo
</select>

同理,如果表的字段名类的属性不一致时,就无法正常赋值了,解决方法和用注解的方式类似


到这里,有关MyBatis的基础操作的介绍就全部讲完了

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • PHP身份证真伪验证、身份证二、三要素核验、身份证ocr接口
  • 【Redis】 关于列表类型
  • 【论文解读】Performance of AV1 Real-Time Mode
  • 软件测试面试题(七)
  • 【ES6】ECMAS6新特性概览(一):变量声明let与const、箭头函数、模板字面量全面解析
  • 代码随想录算法训练营day35 | 122.买卖股票的最佳时机II、55. 跳跃游戏、45.跳跃游戏II
  • Unity中使Main Camera显示Canvas的区域
  • NL6621 实现获取天气情况
  • 数据湖对比(hudi,iceberg,paimon,Delta)
  • 对竞品分析的理解
  • 树与二叉树的概念介绍
  • Python I/O操作笔记
  • 嵌入式之译码器
  • 爬虫之re数据清洗
  • java —— 连接 MySQL 操作
  • ➹使用webpack配置多页面应用(MPA)
  • electron原来这么简单----打包你的react、VUE桌面应用程序
  • Eureka 2.0 开源流产,真的对你影响很大吗?
  • k8s如何管理Pod
  • SQLServer之创建显式事务
  • 从PHP迁移至Golang - 基础篇
  • 翻译:Hystrix - How To Use
  • 使用API自动生成工具优化前端工作流
  • 数据科学 第 3 章 11 字符串处理
  • 它承受着该等级不该有的简单, leetcode 564 寻找最近的回文数
  • 小试R空间处理新库sf
  • 学习笔记DL002:AI、机器学习、表示学习、深度学习,第一次大衰退
  • 鱼骨图 - 如何绘制?
  • 中文输入法与React文本输入框的问题与解决方案
  • Java总结 - String - 这篇请使劲喷我
  • LIGO、Virgo第三轮探测告捷,同时探测到一对黑洞合并产生的引力波事件 ...
  • 智能情侣枕Pillow Talk,倾听彼此的心跳
  • ​2021半年盘点,不想你错过的重磅新书
  • ​补​充​经​纬​恒​润​一​面​
  • #define用法
  • #QT 笔记一
  • #QT(智能家居界面-界面切换)
  • #我与Java虚拟机的故事#连载13:有这本书就够了
  • $NOIp2018$劝退记
  • (1)安装hadoop之虚拟机准备(配置IP与主机名)
  • (9)STL算法之逆转旋转
  • (day6) 319. 灯泡开关
  • (附表设计)不是我吹!超级全面的权限系统设计方案面世了
  • (附源码)springboot 个人网页的网站 毕业设计031623
  • (七)c52学习之旅-中断
  • (四) 虚拟摄像头vivi体验
  • (终章)[图像识别]13.OpenCV案例 自定义训练集分类器物体检测
  • (转载)虚函数剖析
  • .net Application的目录
  • .NET Core使用NPOI导出复杂,美观的Excel详解
  • .net 调用php,php 调用.net com组件 --
  • .NET/C# 避免调试器不小心提前计算本应延迟计算的值
  • .net6解除文件上传限制。Multipart body length limit 16384 exceeded
  • [ CTF ] WriteUp- 2022年第三届“网鼎杯”网络安全大赛(白虎组)
  • [23] GaussianAvatars: Photorealistic Head Avatars with Rigged 3D Gaussians