栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

MyBatis查询数据库

Java 更新时间:发布时间: 百科书网 趣学号
1.MyBatis 是什么?

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

简单来说MyBatis是更简单完成程序和数据库交互的工具,也就是更简单的操作和读取数据库工具。
Mybatis官网:https://mybatis.org/mybatis-3/zh/index.html


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

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

ORM把数据库映射为对象︰

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

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

1.1 创建数据库和表

接下来我们要实现的功能是∶使用MyBatis 的方式来读取用户表中的所有用户,我们使用个人博客的数据库和数据包.具体SQL如下。

-- 创建数据库
drop database if exists mycnblog;
create database mycnblog DEFAULT CHARACTER SET utf8;
-- 使⽤数据数据
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ìnt default 1
);
-- 创建⽂章表
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ìnt default 1
);
-- 创建视频表
drop table if exists videoinfo;
create table videoinfo(
    vid int primary key,
    `title` varchar(250),
    ùrl` varchar(1000),
    createtime datetime default now(),
    updatetime datetime default now(),
    uid int
);
-- 添加⼀个⽤户信息
INSERT INTO `mycnblog`.ùserinfo` (ìd`, ùsername`, `password`, `photo`, 
`createtime`, ùpdatetime`, `state`) VALUES 
(1, 'admin', 'admin', '', '2021-12-06 17:10:48', '2021-12-06 17:10:48', 
1);
-- ⽂章添加测试数据
insert into articleinfo(title,content,uid)
    values('Java','Java正⽂',1);
    
-- 添加视频
insert into videoinfo(vid,title,url,uid) values(1,'java 
title','http://www.baidu.com',1);
1.2 配置连接字符串和MyBatis

此步骤需要进行两项设置,数据库连接字符串设置和MyBatis的XML文件配置。

配置连接字符串
如果是 application.yml 添加如下内容:

# 数据库连接配置
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mycnblog?
characterEncoding=utf8&useSSL=false
    username: root
    password: 940194
    driver-class-name: com.mysql.cj.jdbc.Driver

注意事项:

如果使用 MySQL 是 5.x 之前的使用的是“com.mysql.jdbc.Driver”,如果是⼤于 5.x 使用的是“com.mysql.cj.jdbc.Driver”。

配置 MyBatis 中的 XML 路径
MyBatis 的 XML 中保存是查询数据库的具体操作 SQL,配置如下:

# 配置 mybatis xml 的⽂件路径,在 resources/mapper 创建所有表的 xml ⽂件
mybatis:
  mapper-locations: classpath:mapper/**Mapper.xml

1.3 添加业务代码

下面按照后端开发的工程思路,也就是下面的流程来实现MyBatis查询所有用户的功能:

1.3.1 添加实体类

先添加用户的实体类:

import lombok.Data;
import java.util.Date;

@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    private String photo;
    private Date createTime;
    private Date updateTime;
}
1.3.2 添加mapper接口

数据持久层的接口定义:

import org.apache.ibatis.annotations.Mapper;
import java.util.List;

@Mapper
public interface UserMapper {
    public List getAll();
}
1.3.3 添加 UserMapper.xml

数据持久成的实现,mybatis 的固定 xml 格式:




   

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




    
    select * from userinfo where id=#{id}

3.1.1 参数占位符#{}和${}
  • #{}: 预编译处理。
  • ${}: 字符直接替换。

预编译处理: 在处理#{}时,会将SQL中的#{}替换为?号(例如: “?”),替换后会加上引号,使用PreparedStatement的set方法来赋值。
直接替换∶在处理 ${} 时,就是把 ${}直接替换成变量的值。

3.1.2 ${} 优点


    select * from userinfo where username='${name}' and password='${pwd}'

sql 注⼊代码:“’ or 1='1”

结论:
用于查询的字段,尽量使用#{}预查询的方式。#{}可以防止SQL注入,${}不能防止SQL注入。

3.1.4 like查询

like使用#{}报错


    select username from userinfo where id=#{id}

访问接口执行结果如下:

显示运行了一个查询但没有找到结果映射,也就是说对于select查询标签来说至少需要两个属性.

  • id属性: 用于标识实现接口中的那个方法;
  • 结果映射属性: 结果映射有两种实现标签: resultMap和resultType。
3.2.1 返回类型:resultType

绝大数查询场景可以使用resultType进行返回,如下代码所示:


    select * from userinfo
    
        
            username=#{username}
        
        
            and password=#{password}
        
    

它的优点是使用方便,直接定义到某个实体类即可。

3.2.2 返回字典映射:resultMap

resultMap 使用场景:

  • 字段名称和程序中的属性名不同的情况,可使用resultMap 配置映射;
  • 一对一和一对多关系可以使用resultMap映射并查询数据。

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

程序中的属性如下:

mapper.xml 代码如下:


    select * from userinfo where id=#{id}

查询的结果就有值了,如下图所示:

3.2.3 多表查询

在多表查询时,如果使用resultType标签,在一个类中包含了另一个对象是查询不出来被包含的对象的,比如以下实体类:

@Data
public class ArticleInfo {
    private Integer id;
    private String title;
    private String content;
    private LocalDateTime createtime;
    private LocalDateTime updatetime;
    private Integer rcount;
    // 包含了 userinfo 对象
    private UserInfo user;
}
    
  select a.*,u.username u_username from articleinfo a
  left join userinfo u on a.uid=u.id

以上使用association标签,表示一对一的结果映射:

  • property 属性:指定Article中对应的属性,即用户。
  • resultMap属性∶指定关联的结果集映射,将基于该映射配置来组织用户数据。
  • columnPrefix属性:绑定一对一对象时,是通过
    columnPrefix+association.resultMap.column来映射结果集字段。
    association.resultMap.column是指标签中resultMap属性,对应的结果集映射中,column字段。

注意事项: columnPrefix 不能省略
columnPrefix 如果省略,并且恰好两个表中如果有相同的字段,那么就会导致查询出错,示例如下:

ArticleInfo.java

@Data
public class ArticleInfo {
    private Integer id;
    private String title;
    private String content;
    private LocalDateTime createtime;
    private LocalDateTime updatetime;
    private Integer rcount;
    // 包含了 userinfo 对象
    private UserInfo user;
}

UserInfo.java

@Data
public class UserInfo {
    private int id;
    private String name; // todo:和数据库自定不一致,username
    private String password;
    private String photo;
    private LocalDateTime createtime;
    private LocalDateTime updatetime;
    private int state;
    private List artList;
}

ArticleInfoMapper.xml




    
        
        
        
        
        
        
        
        
        
        
        
    

    
        select a.*,u.id u_id,u.username u_username,u.password u_password from articleinfo a
        left join userinfo u on
        a.uid=u.id
    

    

UserMapper.xml




    
    
        
        
        
        
        
        
        
        
        
        
        
    

    
  select u.*,a.title a_title from userinfo u
  left join articleinfo a on u.id=a.uid where u.id=#{id}

4. 复杂情况:动态SQL使用

动态sql是Mybatis的强大特性之一,能够完成不同条件下不同的sql拼接。
可以参考官方文档:Mybatis动态sql

4.1 标签

在注册用户的时候,可能会有这样⼀个问题,如下图所示:

注册分为两种字段∶必填字段和非必填字段,那如果在添加用户的时候有不确定的字段传入,程序应该如何实现呢?
这个时候就需要使用动态标签来判断了,比如添加的时候性别sex为非必填字段,具体实现如下:


  insert into user(
          username,
          password,
          nickname,
          
            sex,
          
          birthday,
          head
      ) values (
          #{username},
          #{password},
          #{nickname},
          
            #{sex},
          
          #{birthday},
          #{head}
      )

注意test 中的sex,是传入对象中的属性,不是数据库字段。

4.2 标签 -》增(insert)

之前的插入用户功能,只是有一个sex字段可能是选填项,如果有多个字段,一般考虑使用 标签结合 标签,对多个字段都采取动态生成的方式。
标签中有如下属性:

  • prefix: 表示整个语句块,以prefix的值作为前缀
  • suffix: 表示整个语句块,以suffix的值作为后缀
  • prefixOverrides: 表示整个语句块要去除掉的前缀
  • suffixOverrides: 表示整个语句块要去除掉的后缀

调整UserMapper.xml的插入语句为︰


  insert into user
    
        
          username,
        
        
          password,
        
        
          nickname,
        
        
          sex,
        
        
          birthday,
        
        
          head,
        
        
          create_time,
        
    
    
        
          #{username},
        
        
          #{password},
        
        
          #{nickname},
        
        
          #{sex},
        
        
          #{birthday},
        
        
          #{head},
        
        
          #{createTime},
        
    

在以上sql动态解析时,会将第一个 部分做如下处理:

  • 基于prefix配置,开始部分加上(
  • 基于suffix配置,结束部分加上)
  • 多个组织的语句都以,结尾,在最后拼接好的字符串还会以,结尾,会基于suffixOverrides配置去掉最后一个,
  • 注意中的createTime是传入对象的属性
4.5 标签 -》删(delete)

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

  • collection:绑定方法参数中的集合,如List,Set,Map或数组对象
  • item:遍历时的每一个对象
  • open:语句块开头的字符串
  • close:语句块结束的字符串
  • separator:每次遍历之间间隔的字符串

示例∶根据多个文章id来删除文章数据。ArticleMapper中新增接口方法:

int deleteByIds(List ids);

ArticleMapper.xml 中新增删除 sql:


    delete from article
    where id in
    
        #{item}
    

4.4 标签 -》改(update)

根据传⼊的用户对象属性来更新用户数据,可以使用标签来指定动态内容。
UserMapper 接口中修改用户方法:根据传⼊的用户 id 属性,修改其他不为 null 的属性:

int updateById(User user);

UserMapper.xml 中添加更新用户 sql:


    update user
        
            
                username=#{username},
            
            
                password=#{password},
            
            
                nickname=#{nickname},
            
            
                sex=#{sex},
            
            
                birthday=#{birthday},
            
            
                head=#{head},
            
            
                create_time=#{createTime},
            
        
    where id=#{id}

以上标签也可以使用 替换。

4.3 标签 -查(select)

传入的用户对象,根据属性做where条件查询,用户对象中属性不为null的,都为查询条件。如user.username为"a",则查询条件为where username=“a” :

UserMapper接口中新增条件查询方法:

List selectByCondition(User user);

UserMapper.xml 中新增条件查询 sql:


以上标签也可以使⽤ 替换。

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/986882.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号