2024年最全MyBatis 查询数据库_mybatis查询某个库的所有表名,2024年最新我把所有大数据开发第三方库整理成了PDF

img
img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

<artifactId>mysql-connector-java</artifactId> 
<scope>runtime</scope>

**② 在创建新项目时添加:**


![在这里插入图片描述](https://img-blog.csdnimg.cn/831070b7cdb84f68a260726ec6d24b7f.png)


### 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 查询所有用户的功能:  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/0ccc6ab255934625b0e3ef7840bf37a1.png)  
 目录结构:  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/5fe646fa939a43a8a595e2d54583901d.png)


#### 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 getAll();
}


#### 2.4.3 添加 UserMapper.xml


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



<?xml version="1.0" encoding="UTF-8"?>

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



<?xml version="1.0" encoding="UTF-8"?> select * from userinfo

标签说明:


* **`<mapper>`标签**:需要指定 namespace 属性,表示命名空间,值为 mapper 接口的全限定名,包括全包名.类名。
* **`<select>`查询标签**:是用来执行数据库的查询操作的:

 `id`:是和 Interface(接口)中定义的方法名称一样的,表示对接口的具体实现方法。  
 `resultType`:是返回的数据类型,也就是开头我们定义的实体类。


#### 2.4.4 添加 Service


服务层实现代码如下:



@Service
public class UserService {
@Resource
private UserMapper userMapper;
public List 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 into userinfo(username,password,photo,state) values(#{username},#{password},#{photo},1)


> 
> **说明:参数占位符 #{} 和 ${}**
> 
> 
> * `#{}`:预编译处理。
> * `${}`:字符直接替换。  
>  预编译处理是指: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 into userinfo(username,password,photo,state) values(#{username},#{password},#{photo},1)

* `useGeneratedKeys`:这会令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法来取出由数据库内部生成的主键(比如:像 MySQL 和 SQL Server 这样的关系型数据库管理系统的自动递增字段),默认值:false。
* `keyColumn`:设置生成键值在表中的列名,在某些数据库(像 PostgreSQL)中,当主键列不是表中的第一列的时候,是必须设置的。如果生成列不止一个,可以用逗号分隔多个属性名称。
* `keyProperty`:指定能够唯一识别对象的属性,MyBatis 会使用 getGeneratedKeys 的返回值或 insert 语句的 selectKey 子元素设置它的值,默认值:未设置(unset)。如果生成列不止一个,可以用逗号分隔多个属性名称。


### 3.2 删除操作



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



delete from userinfo where id=#{id}

### 3.3 修改操作



update userinfo set username=#{name} where id=#{id}

### 3.4 查询操作


#### 3.4.1 单表查询


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



<select id="getUserById" resultType="com.example.demo.model.UserInfo">
    select *
    from userinfo
    where id = #{id}
</select>

#### 3.4.2 多表查询


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



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


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


![在这里插入图片描述](https://img-blog.csdnimg.cn/e11ad87296464e34a9eb09abc638389a.png)  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/15602a69ff024b0bbc5a091303f3b3db.png)  
 xml 如下:



select * from userinfo where id=#{id}

![在这里插入图片描述](https://img-blog.csdnimg.cn/5286c357f5104238ad771e9936c1acad.png)  
 **② 一对一映射**  
 一对一映射要使用 `<association>` 标签,具体实现如下(一篇文章只对应一个作者):



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

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


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



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

#### 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](https://bbs.csdn.net/topics/618545628)


### 4.1 if 标签





![img](https://img-blog.csdnimg.cn/img_convert/1333000c72820f6c8e645a264a0f3c75.png)
![img](https://img-blog.csdnimg.cn/img_convert/6e9bc70013e5239271867492d30f20db.png)
![img](https://img-blog.csdnimg.cn/img_convert/0e20bcdd29f1359cb74cc2913c558574.png)

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**

SQL使用


动态 sql 是Mybatis的强大特性之一,能够完成不同条件下不同的 sql 拼接。  
 可以参考官方文档:[Mybatis动态sql](https://bbs.csdn.net/topics/618545628)


### 4.1 if 标签





[外链图片转存中...(img-VJTPdpZG-1715632976151)]
[外链图片转存中...(img-tCUdiaiT-1715632976152)]
[外链图片转存中...(img-YnsDoWn8-1715632976152)]

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**

  • 19
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值