关于java:MyBatis教程

4次阅读

共计 5981 个字符,预计需要花费 15 分钟才能阅读完成。

1. 什么是 MyBatis

Myba 是一款优良的长久层框架
MyBatis 防止了简直所有的 JDBC 代码和手动设置参数以及获取后果集的过程,缩小了代码的冗余,缩小程序员的操作。
MyBatis 能够应用简略的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类【Plain Old Java Objects, 一般的 Java 对象】映射成数据库中的记录。
MyBatis 原来是 apache 的一个开源我的项目,叫做 ibatis,2010 年这个我的项目由 apache 迁徙到了 google code,并且改名为 MyBatis
2013 年 11 月官网代码迁徙到 GitHub
MyBatis 中文文档:https://mybatis.net.cn/
GitHub:GitHub – mybatis/mybatis-3: MyBatis SQL mapper framework for Java

2. 长久层

长久层,顾名思义是实现长久化工作的代码块,也就是 Date Access Object(Dao 层)
大多数状况下特地是企业级利用,数据长久化往往也就意味着将内存中的数据保留到磁盘上加以固化,而长久化的实现过程则大多通过各种关系数据库来实现。
不过这里有一个字须要特别强调,也就是所谓的“层”。对于利用零碎而言,数据长久性能大多是必不可少的组成部分。也就是说,咱们的零碎中,曾经人造的具备了“长久层”概念?兴许是,但兴许理论状况并非如此。之所以要独立出一个“长久层”的概念, 而不是“长久模块”,“长久单元”,也就意味着,咱们的零碎架构中,应该有一个绝对独立的逻辑层面,专一于数据长久化逻辑的实现.
与零碎其余局部相对而言,这个层面应该具备一个较为清晰和严格的逻辑边界。(也就是改层就是为了操作数据库而设计的)

3.Mybatis 的作用

Mybatis 就是帮忙程序员将数据存取到数据库外面。
传统的 jdbc 操作 , 有很多反复代码块 . 比方 : 数据取出时的封装 , 数据库的建设连贯等等… , 通过框架能够缩小反复代码, 进步开发效率 .
MyBatis 是一个半自动化的 ORM 框架 (Object Relationship Mapping) –> 对象关系映射
所有的事件,不必 Mybatis 仍旧能够做到,只是用了它,会更加不便更加简略,开发更疾速。

4.MyBatis 的长处

简略易学:自身就很小且简略。没有任何第三方依赖,最简略装置只有两个 jar 文件 + 配置几个 sql 映射文件就能够了,易于学习,易于应用,通过文档和源代码,能够比拟齐全的把握它的设计思路和实现。
灵便:mybatis 不会对应用程序或者数据库的现有设计强加任何影响。sql 写在 xml 里,便于对立治理和优化。通过 sql 语句能够满足操作数据库的所有需要。
解除 sql 与程序代码的耦合:通过提供 DAO 层,将业务逻辑和数据拜访逻辑拆散,使零碎的设计更清晰,更易保护,更易单元测试。sql 和代码的拆散,进步了可维护性。
提供 xml 标签,反对编写动静 sql。
当初支流应用办法

Mybatis 操作数据库的形式

1. 能够通过 xml 文件的形式执行 sql;
2. 能够通过注解的形式执行 SQL;

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

1.SQLSession 传递 SQL 骨架给 MappedStatement
2. 由 MappedStatement 联合骨架和 SQL 参数映射成残缺的 SQL 语句
3. 将残缺的 SQL 语句交给 Executer
4. 执行 SQL 语句
5. 返回后果集给 MappedStatement
6. 封装后果集
7. 将后果集返回给 SQLSession

5. 搭建数据库,sql 脚本,间接在数据库中运行即可

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 程序

7. 单击一下 maven 的刷新按钮

8. 我的项目构造

9. 在 resources 文件夹下创立 application.yml 文件并输出如下内容:

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 数据库

11. 顺次编写 Entity、Dao、Service、Controller 层,还有创立 mapper.xml 文件

1.Entity 包:创立一个 UserEntity 类,内容如下:

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 接口,内容如下:

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 类,内容如下:

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.Controller 包:创立一个 UserController 类,内容为:

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 文件,如下图:

<?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 包的地址,填写本人的就好)

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

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

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

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

正文完
 0