当前位置: 首页 > article >正文

MyBatis 操作数据库入门

目录

前言

1.创建springboot⼯程

2.数据准备 

 3.配置Mybatis数据库连接信息

4.编写SQL语句,进行测试


前言

什么是MyBatis?
MyBatis是⼀款优秀的 持久层 框架,⽤于简化JDBC的开发

Mybatis操作数据库的入门步骤:

1.创建springboot⼯程
2.数据库表准备、实体类
3. 引⼊Mybatis的相关依赖,配置Mybatis(数据库连接信息)
4.编写SQL语句(注解/XML) ,进行测试

 了解更多MyBatis中文网icon-default.png?t=O83Ahttps://mybatis.net.cn/


1.创建springboot⼯程

创建springboot⼯程,并导⼊ mybatis的起步依赖、mysql的驱动包

 项⽬⼯程创建完成后,⾃动在pom.xml⽂件中,导⼊Mybatis依赖和MySQL驱动依赖

spring Boot会 按照自身对应版本导入对应的依赖。比如: SpringBoot 3.X对⽤MyBatis版本为3.X

我导入的依赖版本

<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>3.0.3</version>
</dependency>

<dependency>
   <groupId>com.mysql</groupId>
   <artifactId>mysql-connector-j</artifactId>
   <scope>runtime</scope>
</dependency>
对应的依赖版本参考:

mybatis-spring-boot-autoconfigure – Introductionicon-default.png?t=O83Ahttps://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/ 


2.数据准备 

创建⽤户表

-- 创建数据库

DROP DATABASE IF EXISTS mybatis_test;

CREATE DATABASE mybatis_test DEFAULT CHARACTER SET utf8mb4;

-- 使用数据数据

USE mybatis_test;

-- 创建表[用户表]

DROP TABLE IF EXISTS userinfo;

CREATE TABLE `userinfo` (

        `id` INT ( 11 ) NOT NULL AUTO_INCREMENT,

        `username` VARCHAR ( 127 ) NOT NULL,

        `password` VARCHAR ( 127 ) NOT NULL,

        `age` TINYINT ( 4 ) NOT NULL,

        `gender` TINYINT ( 4 ) DEFAULT '0' COMMENT '1-男 2-女 0-默认',

        `phone` VARCHAR ( 15 ) DEFAULT NULL,

        `delete_flag` TINYINT ( 4 ) DEFAULT 0 COMMENT '0-正常, 1-删除',

        `create_time` DATETIME DEFAULT now(),

        `update_time` DATETIME DEFAULT now(),

        PRIMARY KEY ( `id` )

) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;

-- 添加用户信息

INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )

VALUES ( 'admin', 'admin', 18, 1, '18612340001' );

INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )

VALUES ( 'zhangsan', 'zhangsan', 18, 1, '18612340002' );

INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )

VALUES ( 'lisi', 'lisi', 18, 1, '18612340003' );

INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )

VALUES ( 'wangwu', 'wangwu', 18, 1, '18612340004' );

  

创建对应的实体类 UserInfo
实体类的属性名与表中的字段名⼀⼀对应
import lombok.Data;

import java.util.Date;
@Data
public class Userinfo {
    private Integer id;

    private String username;

    private String password;

    private Byte age;

    private Byte gender;

    private String phone;

    private Byte deleteFlag;

    private Date createTime;

    private Date updateTime;
}
MySQL 开发企业规范

1.表名, 字段名使⽤⼩写字⺟或数字, 单词之间以下划线分割. 尽量避免出现数字开头或者两个下划线 中间只出现数字

 2.表必备三字段: id(主键), create_time(创建时间), update_time(更新时间)

有同等含义的字段即可, 字段名不做强制要求

3.在表查询中, 避免使⽤ * 作为查询的字段列表


 3.配置Mybatis数据库连接信息

具体配置以自身为准

具体表名,密码,用户名以自身为准。 

如果是application.yml⽂件, 配置内容如下:

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
如果是application.yml⽂件, 配置内容如下:
  spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  #数据库连接的url
  spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis_test?
  characterEncoding=utf8&useSSL=false
  #连接数据库的⽤⼾名
  spring.datasource.username=root
  #连接数据库的密码
  spring.datasource.password=root
注意事项:
如果使⽤ MySQL 是 5.x 之前的使⽤的是"com.mysql.jdbc.Driver",如果是⼤于 5.x 使⽤的
是“com.mysql.cj.jdbc.Driver”

4.编写SQL语句,进行测试

在项⽬中, 创建持久层接⼝UserInfoMapper

Mybatis的持久层接⼝规范⼀般都叫 XxxMapper 

UserInfoMapper接口

@Mapper注解:表⽰是MyBatis中的Mapper接⼝,程序运⾏时, 框架会⾃动⽣成接⼝的实现类对象(代理对象),并给交Spring的IOC容器管理

import com.wh.myBatis.model.Userinfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;

@Mapper
public interface UserInfoMapper {

    @Select("select * from userinfo")
    public List<Userinfo> queryAllUser();
}
@Select注解:代表的就是select查询,也就是注解对应⽅法的具体实现内容.

测试

在创建出来的SpringBoot⼯程中,在src下的test⽬录下,已经⾃动帮我们创建好了测试类 ,我们可以 直接使⽤这个测试类来进⾏测试.

 使⽤Idea ⾃动⽣成测试类

在需要测试的Mapper接⼝中, 右键 -> Generate -> Test如下:

1.

2.

3. 

 4.

记得加 @SpringBootTest 注解, 加载Spring运⾏环境 

 代码:

import com.wh.myBatis.model.Userinfo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class UserInfoMapperTest {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Test
    void queryAllUser() {
        for (Userinfo userinfo : userInfoMapper.queryAllUser()) {
            System.out.println(userinfo);
        }

    }
}

结果:


以上为我个人的小分享,如有问题,欢迎讨论!!! 

都看到这了,不如关注一下,给个免费的赞 


http://www.kler.cn/news/337655.html

相关文章:

  • 鸿蒙--知乎评论
  • imx6q 的 header.s的理解
  • Redis list 类型
  • 【JVM调优】JVM高频参数和最优实践
  • 超好用的数据库连接工具-DBeaver连接ClickHouse后找不到系统表?
  • agent实现:通过prompt方式实现agent自定义使用
  • Vue3小兔鲜——订单页
  • 自动驾驶系列—线控悬架技术:自动驾驶背后的动力学掌控者
  • Redis篇(应用案例 - UV统计)(持续更新迭代)
  • 第三十九章 创建安全对话
  • 如何使用 Apt-Get 和 Apt-Cache 在 Ubuntu 和 Debian 中管理软件包
  • 消防隐患在线举报系统开发+ssm论文源码调试讲解
  • Vue 项目文件大小优化
  • 百元头戴式耳机哪款口碑爆棚+质价比高?2024耳机最强推荐攻略!
  • Vue.js组件开发研究
  • 国庆练习(Day24)
  • [OS] 编译 Linux 内核
  • 鲁班到家上门安装维修系统源码开发之结构功能解析
  • 【数据结构】链表-1
  • 力扣 中等 216组合总和III