MyBatis 查询数据库

目录

1.什么是 MyBatis

简单来说 MyBatis更简单完成程序和数据库交互的 具 ,也就是更简单的操作和读取数据库工具。

2.MyBatis 环境搭建

开始搭建 MyBatis 之前,MyBatis 在整个框架中的定位,框架交互流程图:

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

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

ORM 把数据库映射为对象:

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

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

2.1 创建数据库和表

-- 创建数据库drop database if exists mycnblog;create database mycnblog DEFAULT CHARACTER SET utf8mb4;-- 使用数据数据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` int default 1) default charset 'utf8mb4';-- 创建文章表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` int default 1)default charset 'utf8mb4';-- 创建视频表drop table if exists videoinfo;create table videoinfo(  vid int primary key,  `title` varchar(250),  `url` varchar(1000),createtime datetime default now(),updatetime datetime default now(),  uid int)default charset 'utf8mb4';

2.2 添加 MyBatis 框架支持

① 在已有的项目中添加:

org.mybatis.spring.bootmybatis-spring-boot-starter 2.1.4mysqlmysql-connector-java runtime

② 在创建新项目时添加:

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 查询所有用户的功能:

目录结构:

2.4.1 添加实体类

添加用户的实体类:

@Setter@Getter@ToStringpublic 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 接口

数据持久层的接口定义:

@Mapperpublic 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"?> 

标签说明:

展开阅读全文

页面更新:2024-05-08

标签:数据库   框架   属性   接口   对象   操作   标签   代码   数据   用户

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top