Code前端首页关于Code前端联系我们

MyBati基础入门教程:操作数据库七步

terry 2年前 (2023-09-24) 阅读数 60 #后端开发

1.什么是 MyBatis?

MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息、映射接口和 Java 实体类 [Plain Old Java Objects,Plain Java Objects] 到数据库中的记录。

MyBatis 最初是 apache 的一个开源项目,名为 ibatis。 2010年,项目从apache迁移到google code,并更名为MyBatis

2013年11月,官方代码迁移到GitHub

MyBatis中文文档:https://mybatis.net.cn/♷ub: mybatis-3,用于 Java

2 的 MyBatis SQL 映射器框架,下载mybatis-3的源码_GitHub_帮酷持久化层

持久化层,顾名思义,就是完成持久化工作的代码块,即Date Access Object(Dao层)

大多数情况下,尤其是企业级应用中,数据持久化往往意味着将内存中的数据存储到磁盘进行固化,持久化的实现过程大多是通过各种关系数据库来完成的。

不过,这里有一个词需要特别强调,就是所谓的“团队”。对于应用系统来说,数据持久化功能大多是必不可少的组件。也就是说我们的系统原生已经有了“持久层”的概念了?也许吧,但也许事实并非如此。我们之所以要单独创建一个“持久层”的概念,而不是“持久模块”或“持久单元”,是因为我们的系统架构中应该有一个相对独立的逻辑层,专注于数据持久化。逻辑实施。

相对于系统的其他部分,这一层应该有更清晰、更严格的逻辑边界。 (即更改图层是为了服务数据库)

3。 Mybatis

Mybatis的作用是帮助程序员获得对数据库中数据的访问。

传统的jdbc操作有很多重复的代码块。例如:检索数据时的封装、建立与数据库的连接等……,通过框架,可以减少重复代码,提高开发效率。

MyBatis 是一个半自动化的 ORM(对象关系映射)框架 --> 对象关系映射
所有事情没有 Mybatis 仍然可以完成。只要使用它就会更方便、更轻松,开发也会更快。

4。 MyBatis 的优点

易学:体积小、简单。没有第三方依赖项。最简单的安装只需要两个jar文件+几个sql映射文件的配置。它易于学习和使用。通过文档和源码,可以充分理解设计思想和实现。
灵活:mybatis 对应用程序或数据库的现有设计没有影响。 SQL是用xml编写的,可以实现统一管理和优化。所有操作数据库的需求都可以通过sql语句来满足。

将SQL与应用程序代码解耦:提供DAO层,将业务逻辑和数据访问逻辑分离,使系统设计更清晰、更易于维护、更易于单元测试。 SQL和代码的分离提高了可维护性。

提供xml代码,支持编写动态sql。

目前普通的使用方法

Mybati操作数据库的方式

1.可以通过xml文件运行sql;

2。可以通过注解来运行SQL;

Mybatis操作数据库的七种方式大步骤?

1. SQLSession 将 SQL 骨架传递给 MappedStatement

2。 MappedStatement 将骨架和 SQL 参数结合起来,将其映射为完整的 SQL 语句

3。将完整的 SQL 语句提供给执行器

4。执行SQL语句

5。将结果集返回到MappedStatement

6。包装结果集

7。将结果集返回到 SQLSession

5。建好数据库,sql脚本,直接在数据库中运行

MyBatis基础入门教程:操作数据库的七大步骤

CREATE TABLE `user` (  `userId` bigint NOT NULL AUTO_INCREMENT,  `userName` varchar(255) COLLATE utf8mb4_bin NOT NULL,  `userAddress` varchar(255) COLLATE utf8mb4_bin NOT NULL,  PRIMARY KEY (`userId`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

6。创建MyBatis程序

MyBatis基础入门教程:操作数据库的七大步骤

MyBatis基础入门教程:操作数据库的七大步骤

7.单击 Maven 刷新按钮

MyBatis基础入门教程:操作数据库的七大步骤

8。项目结构

MyBatis基础入门教程:操作数据库的七大步骤

9。在资源文件夹中创建application.yml文件,输入以下内容:

MyBatis基础入门教程:操作数据库的七大步骤

server:  port: 8080spring:  datasource:    driver-class-name: com.mysql.cj.jdbc.Driver    url: jdbc:mysql://localhost:3306/test?useUnicode=true & characterEncoding=utf-8 &      useSSL=true & serverTimezone=Asia/Shanghai    username: root    password: 123456mybatis:  mapper-locations: classpath:/Mapper/*.xml  type-aliases-package: com.example.testapi.Entity    //这个是扫描到Entity实体包的路径,可根据自己的配置10.连接自己本地的MySQL数据库

MyBatis基础入门教程:操作数据库的七大步骤

MyBatis基础入门教程:操作数据库的七大步骤

11.依次编写Entity、Dao、Service、Controller层,创建mapper.xml文件

1。实体包:创建一个UserEntity类,内容如下:

MyBatis基础入门教程:操作数据库的七大步骤

public class UserEntity {    private Integer userId;    private String userName;    private String userAddress;    public Integer getUserId() {        return userId;    }    public void setUserId(Integer userId) {        this.userId = userId;    }    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String getUserAddress() {        return userAddress;    }    public void setUserAddress(String userAddress) {        this.userAddress = userAddress;    }}

2。 Dao 包:创建 UserDao 接口,内容如下:

MyBatis基础入门教程:操作数据库的七大步骤

package com.example.testapi.Dao;import com.example.testapi.Entity.UserEntity;import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapperpublic interface UserDao {    List<UserEntity> queryLimit(Integer currentPage, Integer pageSize);    Integer addUser(UserEntity user);    Integer updateUser(UserEntity user);    Integer deleteUser(UserEntity user);}

3.Service 包:创建 UserService 类,内容如下:

MyBatis基础入门教程:操作数据库的七大步骤

package com.example.testapi.Service;import com.example.testapi.Dao.UserDao;import com.example.testapi.Entity.UserEntity;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Service("UserService")public class UserService {    @Autowired    private UserDao userDao;    public List<UserEntity> queryLimit(Integer currentPage,Integer pageSzie){        return userDao.queryLimit(currentPage,pageSzie);    }    public Integer addUser(UserEntity user){        return userDao.addUser(user);    }    public Integer updateUser(UserEntity user){        return userDao.updateUser(user);    }    public Integer deleteUser(UserEntity user){        return userDao.deleteUser(user);    }}

4.Control 包:创建 UserController 类,内容如下:

MyBatis基础入门教程:操作数据库的七大步骤

package com.example.testapi.Controller;import com.example.testapi.Entity.UserEntity;import com.example.testapi.Service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import java.util.List;@RestController@RequestMapping("user")public class UserController {    @Autowired    private UserService userService;    String message = "";    @RequestMapping("/queryLimit")    public List<UserEntity> queryLimit(@RequestParam("currentPage") Integer currentPage,@RequestParam("pageSize") Integer pageSize){        return userService.queryLimit(currentPage,pageSize);    }    @PostMapping("/addUser")    public String addUer(@RequestBody UserEntity user){        //用Mybatis执行insert语句的时候,插入成功会返回1,不成功则会抛出异常,捕获一下异常就好        try {            userService.addUser(user);            message = "增加用户成功";        }catch (Exception exception){            message = "增加用户异常";        }        return message;    }    @PutMapping("/updateUser")    public String updateUser(@RequestBody UserEntity user){        //Mybatis的更新操作成功返回1,用户不存在返回0,失败则抛异常        try {            message = userService.updateUser(user) == 1?"更新用户成功":"用户不存在,更新失败";        }catch (Exception exception){            message = "更新异常";        }        return message;    }    @DeleteMapping("/deleteUser")    public String deleteUser(@RequestBody UserEntity user){        //Mybatis的删除操作和更新返回值一样,成功返回1,用户不存在返回0,失败则抛异常        try {            message = userService.deleteUser(user) == 1?"删除用户成功":"用户不存在,删除失败";        }catch (Exception exception){            message = "删除异常";        }        return message;    }}

12.写完上面的内容后,我们需要将其添加到Mapper文件中。文件夹下创建mapper.xml文件,如下图:

MyBatis基础入门教程:操作数据库的七大步骤

<?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.testapi.Dao.UserDao">    <select id="queryLimit" resultType="UserEntity">        select * from user limit #{currentPage},#{pageSize};    </select>    <insert id="addUser" parameterType="UserEntity">        insert into user(userName,userAddress) values(#{userName},#{userAddress});    </insert>    <update id="updateUser" parameterType="UserEntity">        update user set userName=#{userName},userAddress=#{userAddress} where userId=#{userId};    </update>    <delete id="deleteUser" parameterType="UserEntity">        delete from user where userId=#{userId};    </delete></mapper>13.最后我们需要在启动类加一点东西(MapperScan扫描的是我们Dao包的地址,填写自己的就好)

MyBatis基础入门教程:操作数据库的七大步骤

14。测试接口添加用户数据 -> 地址为:http://localhost:8080/user/addUser

MyBatis基础入门教程:操作数据库的七大步骤

搜索用户数据 -> 地址为:http://localhost:8080/user/queryLimit?currentPage= 0&pageSize = 5

MyBatis基础入门教程:操作数据库的七大步骤

更新用户数据 -> 地址为:http://localhost:8080/user/updateUser

MyBatis基础入门教程:操作数据库的七大步骤

删除用户数据 -> 地址为:http://localhost:8080/user/deleteUser

MyBatis基础入门教程:操作数据库的七大步骤

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门