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

【Mybatis】Mybatis操作数据库

mybatis 导入

mybatis是一种持久层框架,支持自定义SQL、存储过程、高级映射(自动把“数据库表格”变成Java对象

在使用mybatis之前,需要引入mybatis相关依赖,配置mybatis和数据库连接信息

pom.xml 相关依赖

(mybatis依赖、sql驱动包)

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

application.yml 配置

数据库、mybatis配置

spring:application:name: mybatis_demo# 数据库配置datasource:url: jdbc:mysql://localhost:3306/数据库名?characterEncoding=utf8&useSSL=falseusername: rootpassword: root driver-class-name: com.mysql.cj.jdbc.Driver# mybatis配置
mybatis:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 日志的打印map-underscore-to-camel-case: true # 驼峰自动转换mapper-locations: classpath:mapper/**Mapper.xml

mybatis 操作数据库

mybatis操作数据库,有两种实现方式,一种是使用@Mapper注解,另一种是使用xxMapper.xml

@Mapper注解

@Mapper注解,是mybatis提供的,就是将加了@Mapper注解的对象,交给spring进行管理。这样我们才能直接@Autowired使用这个对象

在各各注解括号里面,编写sql语句

@Select

@Select("select * from user where id = #{id}") // 第一个id是数据库user表中的id字段;第二个id就是下面括号传入的参数名,需要保持一致
UserInfo selectUserById(int id); // 括号里的参数,是查询条件,这是属性名,这个属性名可以任意写:id、value、num...
#{ }

select * from user where id = #{id},使用了#{ },里面的值就是动态值,输入值由用户决定

#{ }:是预编译,会替换为?进行占位,提前对sql进行编译,然后将参数填充到sql语句中;能防止sql注入

${ }

${ }:是即时编译会直接进行字符串替换,一起对sql进行编译。但是当参数是字符串时,需要添加 ' ',但是${ }不会拼接引号。

${ }:的使用场景 -> 排序功能(order by)、当表名作为参数时,也只能使用${ }

concat()

当在使用like查询时,使用#{ }会报错;使用${ }可以查询出来,但是会存在sql注入问题

就可以使用MySQL的内置函数concat() -> like concat('%',#{key},'%')

Test代码:
@Testvoid selectUserById() {UserInfo userInfo1 = userInfoMapper.selectUserById(3); // userInfoMapper对象 由@Autowired进行获取System.out.println(userInfo1);}

@Insert

@Options(useGeneratedKeys = true, keyProperty = "user.id") // @Options 使用注解,获取到自增id
@Insert("insert into user (name, age, gender, address) values(#{user.name}, #{user.age}, #{user.gender}, #{user.address})")
Integer insertUserInfo(@Param("user") UserInfo userInfo); // @Param 用于参数重命名,修改后,sql要用重新命名的名字
@Options

@Options(useGenerateKeys = true, keyProperty = "id") 用于获取自增id,此处括号里面,表示的是哪个类里面的id

@Param

@Param用于参数重命名,此处是将参数userInfo的名字,重命名为user,则sql也需要用重命名后的名字

Test代码:
@Testvoid insertUserInfo() {userInfo.setName("新增"); // userInfo 是通过UserInfo类,new的一个对象userInfo.setAge(100);userInfo.setGender("女");userInfo.setAddress("使用@Options获取id");Integer row = userInfoMapper.insertUserInfo(userInfo); // userInfoMapper对象 由@Autowired进行获取Integer id = userInfo.getId();System.out.println("新增行:" + row);System.out.println("id = :" + id);}

@Delete

@Delete("delete from user where age = #{age}")
int deleteUser(int age);

#{ }:使用预编译占位符,动态获取值

Test代码:
@Testvoid deleteUser() {int num = userInfoMapper.deleteUser(30); // userInfoMapper对象 由@Autowired进行获取System.out.println(num);}

@Update

@Update("update user set name = #{name} where gender = #{gender}")
int updateUserInfo(UserInfo userInfo);
Test代码:
@Testvoid updateUserInfo() {userInfo.setName("新增数据"); // userInfo 是通过UserInfo类,new的一个对象userInfo.setGender("女");int num = userInfoMapper.updateUserInfo(userInfo); // userInfoMapper对象 由@Autowired进行获取System.out.println(num);}

xxMapper.xml

使用mybatis的xml配置,需要配置 mybatis xml 的文件路径,在 resources/mapper 创建所有表的 xml 文件。

mapper-locations: classpath:mapper/**Mapper.xml    # **表示的就是类名

.xml方式,有两个步骤

1、定义方法:interface (需要加上@Mapper注解)

2、方法实现:**Mapper.xml 

**Mapper.xml 的固定格式

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- 1. 命名空间 = 对应 Dao/Mapper 接口全限定名 包名.类名-->
<mapper namespace="zxh.mybatis_demo.mapper.**MapperXML"><!-- 编写sql代码 -->    </mapper>

<select></select>

interface,定义方法
List<UserInfo> selectUserByGender(String gender);
**Mapper.xml 实现方法
<select id="selectUserByGender" resultType="zxh.mybatis_demo.mode.UserInfo">select * from user where gender = #{gender}
</select>

id:interface接口中定义的方法名一致,表示对接口的具体实现方法

resultType:返回的数据类型

Test代码:
@Testvoid updateUserInfoTest() {int num = userInfoMapperXML.updateUserInfo(13); // userInfoMapperXML对象 由@Autowired进行获取System.out.println(num);}

<insert></insert>

interface,定义方法
Integer insertUser(UserInfo userInfo);
**Mapper.xml实现方法
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">insert into user (name, age, gender, address) values (#{name}, #{age}, #{gender}, #{address})</insert>
Test代码:
@Testvoid insertUser() {userInfo.setName("使用xml方式"); // userInfo 是通过UserInfo类,new的一个对象userInfo.setAge(30);userInfo.setGender("女");userInfo.setAddress("insertUser");Integer row = userInfoMapperXML.insertUser(userInfo); // userInfoMapperXML对象 由@Autowired进行获取Integer id = userInfo.getId();System.out.println("影响行:" + row);System.out.println("id:" + id);}

<delete></delete>

interface,定义方法
    Integer deleteUserInfo(String gender);
**Mapper.xml实现方法
<delete id="deleteUserInfo">delete from user where gender = #{gender}</delete>
Test代码:
@Testvoid deleteUserInfo() {Integer num = userInfoMapperXML.deleteUserInfo("女");System.out.println(num);}

<update></update>

interface,定义方法
Integer updateUserInfo(UserInfo userInfo);
**Mapper.xml实现方法
<update id="updateUserInfo">update user set name = #{name}, address = #{address} where id = #{id};</update>
Test代码:
@Testvoid updateUserInfoTest() {userInfo.setName("没获取到值");userInfo.setAddress("那值去哪儿了");userInfo.setId(5);int num = userInfoMapperXML.updateUserInfo(userInfo); // userInfoMapperXML对象 由@Autowired进行获取System.out.println(num);}
http://www.dtcms.com/a/487459.html

相关文章:

  • PI详细介绍了800V DC的Powigan优势
  • s4栈学习和链栈的实现
  • 阿里云建站后台国际新闻最新报道
  • Linux操作系统学习之---进程信号的产生和保存
  • React Hooks 核心原理与开发技巧
  • 海南手机网站建设公司哪家好深圳营销型网站seo
  • 丽江市建设局网站深圳市城乡和建设局网站首页
  • 南昌做公司网站哪家好生物做实验的网站
  • RHCSA 基础练习
  • Learn C the Hardway学习笔记和拓展知识(一)
  • 算法10.0
  • 凡科网做的网站能直接用吗网站换服务器对排名有影响吗
  • 多层超表面革新 | 简化传统光学系统
  • 辽阳专业建设网站公司电话山东住房城乡建设厅网站首页
  • 数据结构2:线性表1-线性表类型及其特点
  • 网站外包如何报价做那种事的网站
  • 张家港做网站的推荐驻马店app和网站开发公司
  • 目标检测(一)
  • 石家庄免费做网站专做药材的网站有哪些
  • 基本功 | 一文讲清多线程和多线程同步
  • 360门户网站怎样做广州百度seo代理
  • C++蓝桥杯之函数与递归
  • Oracle AWR报告分析:诊断RAC Global cache log flush性能故障
  • python - 第四天
  • 领取流量网站药剂学教学网站的建设
  • 端端网站开发网络广告网站怎么做
  • threejs(五)纹理贴图、顶点UV坐标
  • debug - MDK - arm-none-eabi - 将MDK工程编译过程的所有命令行参数找出来
  • 网站怎么维护百度会收录双域名的网站么
  • Oracle数据库基本命令的8个模块