百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

MyBatis 查询数据库(mybatis查询数据库代码)

bigegpt 2024-08-01 11:50 4 浏览

目录

1.什么是 MyBatis

  • MyBatis 是一款优秀的持久层框架,它?持 自定义 SQL存储过程 以及 高级映射
  • MyBatis 去除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
  • MyBatis 可以通过简单的 XML注解 来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

简单来说 MyBatis更简单完成程序和数据库交互的?具 ,也就是更简单的操作和读取数据库工具。

2.MyBatis 环境搭建

开始搭建 MyBatis 之前,MyBatis 在整个框架中的定位,框架交互流程图:

MyBatis 也是一个 ORM 框架,ORM(Object Relational Mapping),即对象关系映射。在面向对象编程语?中, 将关系型数据库中的数据与对象建立起映射关系 ,进而自动的完成 数据与对象的互相转换

  1. 将输入数据(即传入对象)+SQL 映射成原生 SQL
  2. 将结果集映射为返回对象,即输出对象

ORM 把数据库映射为对象:

  1. 数据库表(table)–> 类(class)
  2. 记录(record,行数据)–> 对象(object)
  3. 字段(field) --> 对象的属性(attribute)

一般的 ORM 框架,会将数据库模型的每张表都映射为一个 Java 类。 也就是说使用 MyBatis 可以像操作对象?样来操作数据库中的表,可以实现对象和数据库表之间的转换。

2.1 创建数据库和表

-- 创建数据库
drop database if exists mycnblog;
create database mycnblog DEFAULT CHARACTER SET utf8mb4;

-- 使用数据数据
use mycnblog;

-- 创建表[用户表]
drop table if exists  userinfo;
create table userinfo(
    id int primary key auto_increment,
    username varchar(100) not null,
    password varchar(32) not null,
    photo varchar(500) default '',
    createtime datetime default now(),
    updatetime datetime default now(),
    `state` int default 1
) default charset 'utf8mb4';

-- 创建文章表
drop table if exists  articleinfo;
create table articleinfo(
    id int primary key auto_increment,
    title varchar(100) not null,
    content text not null,
    createtime datetime default now(),
    updatetime datetime default now(),
    uid int not null,
    rcount int not null default 1,
    `state` int default 1
)default charset 'utf8mb4';

-- 创建视频表
drop table if exists videoinfo;
create table videoinfo(
  	vid int primary key,
  	`title` varchar(250),
  	`url` varchar(1000),
		createtime datetime default now(),
		updatetime datetime default now(),
  	uid int
)default charset 'utf8mb4';

2.2 添加 MyBatis 框架支持

① 在已有的项目中添加:

<!-- 添加 MyBatis 框架 -->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId> 
	<version>2.1.4</version>
</dependency>
<!-- 添加 MySQL 驱动 -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId> 
	<scope>runtime</scope>
</dependency>

② 在创建新项目时添加:

2.3 配置数据库连接和MyBatis

在 application.yml 配置数据库连接:

# 配置数据库连接
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1/mycnblog?charsetEncoding=utf8
    username: root
    password: 12345678
    driver-class-name: com.mysql.cj.jdbc.Driver

配置 MyBatis 中的 XML 路径:

# 设置Mybatis的xml保存路径
mybatis:
  mapper-locations: classpath:mybatis/**Mapper.xml

2.4 添加代码

按照后端开发的工程思路来实现 MyBatis 查询所有用户的功能:

目录结构:

2.4.1 添加实体类

添加用户的实体类:

@Setter
@Getter
@ToString
public class UserInfo {
 
    private int id;
    private String username;
    private String password;
    private String photo;
    private String createtime;
    private String updatetime;
    private int state;
}

2.4.2 添加 mapper 接口

数据持久层的接口定义:

@Mapper
public interface UserMapper {
 
	public List<UserInfo> getAll(); 
}

2.4.3 添加 UserMapper.xml

数据持久层的实现,mybatis 的固定 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.UserMapper"> 
</mapper>

UserMapper.xml 查询所有用户的具体实现 SQL:

<?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.UserMapper">
	<select id="getAll" resultType="com.example.demo.model.UserInfo"> 
        select * from userinfo
	</select> 
</mapper>

标签说明:

  • <mapper> 标签 :需要指定 namespace 属性,表示命名空间,值为 mapper 接口的全限定名,包括全包名.类名。
  • <select> 查询标签 :是用来执行数据库的查询操作的:
  • id :是和 Interface(接口)中定义的方法名称?样的,表示对接口的具体实现方法。
  • resultType :是返回的数据类型,也就是开头我们定义的实体类。

2.4.4 添加 Service

服务层实现代码如下:

@Service
public class UserService {
 
	@Resource
	private UserMapper userMapper; 
	public List<UserInfo> getAll() {
 
		return userMapper.getAll();
    } 
}

2.4.5 添加 Controller

控制器层的实现代码如下:

@RestController
@RequestMapping("/user")
public class UserController {
 
    @Resource
    private UserService userService;

    @RequestMapping("/getuserbyid")
    public UserInfo getUserById(Integer id) {
 
        if (id != null && id > 0) {
 
            return userService.getUserById(id);
        } else {
 
            return new UserInfo();
        }
    }
}

3.MyBatis 增删改查操作

操作步骤:

  • 添加 controller
  • 添加 service
  • 添加 mapper (dao)
  • 添加 xml

3.1 增加操作

① 添加 controller:

@RequestMapping("/insert")
    public Integer insert(UserInfo userInfo) {
 
        return userService.insert(userInfo);
    }

② 添加 service:

public Integer insert(UserInfo userInfo) {
 
        return userMapper.insert(userInfo);
    }

③ 添加 mapper :

Integer insert(UserInfo userInfo);

④ 添加 xml:

<insert id="add">
  insert into userinfo(username,password,photo,state) 
  values(#{username},#{password},#{photo},1)
</insert>

说明:参数占位符 #{} 和 ${}

  • #{} :预编译处理。
  • ${} :字符直接替换。
    预编译处理是指:MyBatis 在处理#{}时,
    会将 SQL 中的 #{} 替换为 ? 号 ,使用用PreparedStatement 的set 方法来赋值。直接替换:是MyBatis 在处理 ${} 时, 就是把 ${} 替换成 变量的值

特殊的增加

默认情况下返回的是受影响的行号,如果想要 返回自增 id ,具体实现如下:

controller 实现代码:

public Integer add2(@RequestBody UserInfo userInfo) {
 
	userService.getAdd2(userInfo); 
	return user.getId();
}

mapper 接口:

@Mapper
public interface UserMapper {
 
	// 添加,返回?增id 
	void add2(User user);
}

mapper.xml 实现如下:

<insert id="add2" useGeneratedKeys="true" keyProperty="id"> 
    insert into userinfo(username,password,photo,state) 
    values(#{username},#{password},#{photo},1)
</insert>
useGeneratedKeys
keyColumn
keyProperty

3.2 删除操作

前面三个步骤操作类似,重点看下第四步,数据持久层的实现(xml)。

<delete id="delById" parameterType="java.lang.Integer"> 
    delete from userinfo where id=#{id}
</delete>

3.3 修改操作

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

3.4 查询操作

3.4.1 单表查询

查询操作需要设置返回类型,绝大数查询场景可以使? resultType 进行返回,它的优点是使用方便,直接定义到某个实体类即可。

<!-- 查询单条数据(根据id)-->
    <select id="getUserById" resultType="com.example.demo.model.UserInfo">
        select *
        from userinfo
        where id = #{id}
    </select>

3.4.2 多表查询

但有些场景就需要用到返回字典映射( resultMap )比如:

  • 字段名称和程序中的属性名不同的情况;
  • ?对?和?对多关系。

① 字段名和属性名不同的情况

xml 如下:

<resultMap id="BaseMap" type="com.example.demo.model.UserInfo"> 
<id column="id" property="id"></id>
<result column="username" property="username"></result> 
<result column="password" property="pwd"></result>
</resultMap>
<select id="getUserById"
resultMap="com.example.demo.mapper.UserMapper.BaseMap"> 
    select * from userinfo where id=#{id}
</select>

② 一对一映射

一对一映射要使用 <association> 标签,具体实现如下(一篇文章只对应一个作者):

<resultMap id="BaseMap" type="com.example.demo.model.ArticleInfo">
	<id property="id" column="id"></id>
	<result property="title" column="title"></result>
	<result property="content" column="content"></result>
	<result property="createtime" column="createtime"></result>
	<result property="updatetime" column="updatetime"></result>
	<result property="uid" column="uid"></result>
	<result property="rcount" column="rcount"></result>
	<result property="state" column="state"></result>
	<association property="user"
		resultMap="com.example.demo.mapper.UserMapper.BaseMap" 
		columnPrefix="u_">
	</association> 
</resultMap>
<select id="getAll" resultMap="BaseMap">
  select a.*,u.username u_username from articleinfo a 
  left join userinfo u on a.uid=u.id
</select>
  • property 属性:指定 Article 中对应的属性,即用户。
  • resultMap 属性:指定关联的结果集映射,将基于该映射配置来组织用户数据。
  • columnPrefix 属性:绑定一对一对象时,是通过
    columnPrefix+association.resultMap.column 来映射结果集字段。

③ 一对多映射

一对多需要使用 <collection> 标签,用法和 <association> 相同,如下所示:

<resultMap id="BaseMap" type="com.example.demo.model.UserInfo"> 
	<id column="id" property="id" />
	<result column="username" property="username"></result> 
	<result column="password" property="password"></result> 
	<result column="photo" property="photo"></result>
	<collection property="alist"
		resultMap="com.example.demo.mapper.ArticleInfoMapper.BaseMap"
		columnPrefix="a_">
	</collection> 
</resultMap>
<select id="getUserById" resultMap="BaseMap"> 
  select u.*,a.title a_title from userinfo u
  left join articleinfo a on u.id=a.uid where u.id=#{id}
</select>

3.4.3 like查询

like 使用 #{} 会报错,可以考虑使用 mysql 的内置函数 concat() 来处理,实现代码如下:

<select id="getUserByLikeName" resultType="com.example.demo.model.UserInfo">
        select *
        from userinfo
        where username like concat('%', #{username}, '%')
    </select>

4.动态SQL使用

动态 sql 是Mybatis的强大特性之一,能够完成不同条件下不同的 sql 拼接。

可以参考官方文档: Mybatis动态sql

4.1 if 标签

<insert id="add3">
        insert into userinfo(username,
        <if test="photo!=null">
            photo,
        </if>
        password)
        values (#{username},
        <if test="photo!=null">
            #{photo},
        </if>
        #{password})
    </insert>

test中的对象是传入对象的属性,当它不为空时,才拼接里面的内容。

4.2 trim 标签

<trim> 标签中有如下属性:

prefix
suffix
prefixOverrides
suffixOverrides

示例:

<insert id="add4">
        insert into userinfo
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username!=null">
                username,
            </if>
            <if test="photo!=null">
                photo,
            </if>
            <if test="password!=null">
                password
            </if>
        </trim>
        values
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username!=null">
                #{username},
            </if>
            <if test="photo!=null">
                #{photo},
            </if>
            <if test="password!=null">
                #{password}
            </if>
        </trim>
    </insert>

4.3 where 标签

传入的用户对象,根据属性做where条件查询,用户对象中属性不为 null 的,都为查询条件。

  • <where> 标签, 如果有查询条件就会生成where, 如果没有查询条件就不会生成where
  • <where> 会判断第一个条件前面有没有 and , 如果有就会去掉.
<select id="getList" resultMap="BaseMap">
        select * from userinfo
        <where>
            <if test="username!=null">
                username=#{username}
            </if>
            <if test="password!=null">
                and password=#{password}
            </if>
        </where>
    </select>

4.4 set 标签

更新的时候也会出现问题, 使用 <set> 标签来解决(与 <where> 标签类似):

<update id="updateById">
        update userinfo
        <set>
            <if test="username!=null">
                username=#{username},
            </if>
            <if test="password!=null">
                password=#{password}
            </if>
        </set>
        where id=#{id}
    </update>

4.5 foreach 标签

对集合进行遍历时可以使用该标签。标签有如下属性:

collection
item
open
close
separator

示例:

<delete id="delete">
        delete from userinfo where id in
        <foreach collection="list" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </delete>

相关推荐

得物可观测平台架构升级:基于GreptimeDB的全新监控体系实践

一、摘要在前端可观测分析场景中,需要实时观测并处理多地、多环境的运行情况,以保障Web应用和移动端的可用性与性能。传统方案往往依赖代理Agent→消息队列→流计算引擎→OLAP存储...

warm-flow新春版:网关直连和流程图重构

本期主要解决了网关直连和流程图重构,可以自此之后可支持各种复杂的网关混合、多网关直连使用。-新增Ruoyi-Vue-Plus优秀开源集成案例更新日志[feat]导入、导出和保存等新增json格式支持...

扣子空间体验报告

在数字化时代,智能工具的应用正不断拓展到我们工作和生活的各个角落。从任务规划到项目执行,再到任务管理,作者深入探讨了这款工具在不同场景下的表现和潜力。通过具体的应用实例,文章展示了扣子空间如何帮助用户...

spider-flow:开源的可视化方式定义爬虫方案

spider-flow简介spider-flow是一个爬虫平台,以可视化推拽方式定义爬取流程,无需代码即可实现一个爬虫服务。spider-flow特性支持css选择器、正则提取支持JSON/XML格式...

solon-flow 你好世界!

solon-flow是一个基础级的流处理引擎(可用于业务规则、决策处理、计算编排、流程审批等......)。提供有“开放式”驱动定制支持,像jdbc有mysql或pgsql等驱动,可...

新一代开源爬虫平台:SpiderFlow

SpiderFlow:新一代爬虫平台,以图形化方式定义爬虫流程,不写代码即可完成爬虫。-精选真开源,释放新价值。概览Spider-Flow是一个开源的、面向所有用户的Web端爬虫构建平台,它使用Ja...

通过 SQL 训练机器学习模型的引擎

关注薪资待遇的同学应该知道,机器学习相关的岗位工资普遍偏高啊。同时随着各种通用机器学习框架的出现,机器学习的门槛也在逐渐降低,训练一个简单的机器学习模型变得不那么难。但是不得不承认对于一些数据相关的工...

鼠须管输入法rime for Mac

鼠须管输入法forMac是一款十分新颖的跨平台输入法软件,全名是中州韵输入法引擎,鼠须管输入法mac版不仅仅是一个输入法,而是一个输入法算法框架。Rime的基础架构十分精良,一套算法支持了拼音、...

Go语言 1.20 版本正式发布:新版详细介绍

Go1.20简介最新的Go版本1.20在Go1.19发布六个月后发布。它的大部分更改都在工具链、运行时和库的实现中。一如既往,该版本保持了Go1的兼容性承诺。我们期望几乎所...

iOS 10平台SpriteKit新特性之Tile Maps(上)

简介苹果公司在WWDC2016大会上向人们展示了一大批新的好东西。其中之一就是SpriteKitTileEditor。这款工具易于上手,而且看起来速度特别快。在本教程中,你将了解关于TileE...

程序员简历例句—范例Java、Python、C++模板

个人简介通用简介:有良好的代码风格,通过添加注释提高代码可读性,注重代码质量,研读过XXX,XXX等多个开源项目源码从而学习增强代码的健壮性与扩展性。具备良好的代码编程习惯及文档编写能力,参与多个高...

Telerik UI for iOS Q3 2015正式发布

近日,TelerikUIforiOS正式发布了Q32015。新版本新增对XCode7、Swift2.0和iOS9的支持,同时还新增了对数轴、不连续的日期时间轴等;改进TKDataPoin...

ios使用ijkplayer+nginx进行视频直播

上两节,我们讲到使用nginx和ngixn的rtmp模块搭建直播的服务器,接着我们讲解了在Android使用ijkplayer来作为我们的视频直播播放器,整个过程中,需要注意的就是ijlplayer编...

IOS技术分享|iOS快速生成开发文档(一)

前言对于开发人员而言,文档的作用不言而喻。文档不仅可以提高软件开发效率,还能便于以后的软件开发、使用和维护。本文主要讲述Objective-C快速生成开发文档工具appledoc。简介apple...

macOS下配置VS Code C++开发环境

本文介绍在苹果macOS操作系统下,配置VisualStudioCode的C/C++开发环境的过程,本环境使用Clang/LLVM编译器和调试器。一、前置条件本文默认前置条件是,您的开发设备已...