前言
记录时间:2023.3.31
已坚持学习第33天
java从入门到精通
学习java时间历程记录打卡
早上7:00到 12:00
下午2:00到 5:00
JavaWeb-mybatis基础操作总结
完成代码练习
SQL数据库表创建
create table user(
id int unsigned primary key auto_increment comment 'ID',
name varchar(100) comment '姓名',
age tinyint unsigned comment '年龄',
gender tinyint unsigned comment '性别, 1:男, 2:女',
phone varchar(11) comment '手机号'
) comment '用户表';
insert into user(id, name, age, gender, phone) VALUES (null,'白眉鹰王',55,'1','18800000000');
insert into user(id, name, age, gender, phone) VALUES (null,'金毛狮王',45,'1','18800000001');
insert into user(id, name, age, gender, phone) VALUES (null,'青翼蝠王',38,'1','18800000002');
insert into user(id, name, age, gender, phone) VALUES (null,'紫衫龙王',42,'2','18800000003');
insert into user(id, name, age, gender, phone) VALUES (null,'光明左使',37,'1','18800000004');
insert into user(id, name, age, gender, phone) VALUES (null,'光明右使',48,'1','18800000005');
select * from user;
-- 部门管理
create table dept(
id int unsigned primary key auto_increment comment '主键ID',
name varchar(10) not null unique comment '部门名称',
create_time datetime not null comment '创建时间',
update_time datetime not null comment '修改时间'
) comment '部门表';
insert into dept (id, name, create_time, update_time) values(1,'学工部',now(),now()),(2,'教研部',now(),now()),(3,'咨询部',now(),now()), (4,'就业部',now(),now()),(5,'人事部',now(),now());
-- 员工管理
create table emp (
id int unsigned primary key auto_increment comment 'ID',
username varchar(20) not null unique comment '用户名',
password varchar(32) default '123456' comment '密码',
name varchar(10) not null comment '姓名',
gender tinyint unsigned not null comment '性别, 说明: 1 男, 2 女',
image varchar(300) comment '图像',
job tinyint unsigned comment '职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师',
entrydate date comment '入职时间',
dept_id int unsigned comment '部门ID',
create_time datetime not null comment '创建时间',
update_time datetime not null comment '修改时间'
) comment '员工表';
INSERT INTO emp(id, username, password, name, gender, image, job, entrydate,dept_id, create_time, update_time) VALUES
(1,'jinyong','123456','金庸',1,'1.jpg',4,'2000-01-01',2,now(),now()),
(2,'zhangwuji','123456','张无忌',1,'2.jpg',2,'2015-01-01',2,now(),now()),
(3,'yangxiao','123456','杨逍',1,'3.jpg',2,'2008-05-01',2,now(),now()),
(4,'weiyixiao','123456','韦一笑',1,'4.jpg',2,'2007-01-01',2,now(),now()),
(5,'changyuchun','123456','常遇春',1,'5.jpg',2,'2012-12-05',2,now(),now()),
(6,'xiaozhao','123456','小昭',2,'6.jpg',3,'2013-09-05',1,now(),now()),
(7,'jixiaofu','123456','纪晓芙',2,'7.jpg',1,'2005-08-01',1,now(),now()),
(8,'zhouzhiruo','123456','周芷若',2,'8.jpg',1,'2014-11-09',1,now(),now()),
(9,'dingminjun','123456','丁敏君',2,'9.jpg',1,'2011-03-11',1,now(),now()),
(10,'zhaomin','123456','赵敏',2,'10.jpg',1,'2013-09-05',1,now(),now()),
(11,'luzhangke','123456','鹿杖客',1,'11.jpg',5,'2007-02-01',3,now(),now()),
(12,'hebiweng','123456','鹤笔翁',1,'12.jpg',5,'2008-08-18',3,now(),now()),
(13,'fangdongbai','123456','方东白',1,'13.jpg',5,'2012-11-01',3,now(),now()),
(14,'zhangsanfeng','123456','张三丰',1,'14.jpg',2,'2002-08-01',2,now(),now()),
(15,'yulianzhou','123456','俞莲舟',1,'15.jpg',2,'2011-05-01',2,now(),now()),
(16,'songyuanqiao','123456','宋远桥',1,'16.jpg',2,'2010-01-01',2,now(),now()),
(17,'chenyouliang','123456','陈友谅',1,'17.jpg',NULL,'2015-03-21',NULL,now(),now());
-- 根据ID删除数据
delete from emp where id = 17;
-- 登录
select count(*) from emp where username = 'zhangwuji' and password = '123456';
select count(*) from emp where username = 'zhangwuji' and password = '111';
-- SQL注入
select count(*) from emp where username = 'wuieuwiueiwuiew' and password = '' or '1' = '1';
mybatis入门操作
1.目录结构
2.定义类
package cn.vqqc.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
private Integer id; //ID
private String username; //用户名
private String password; //密码
private String name; //姓名
private Short gender; //性别, 1 男, 2 女
private String image; //图像url
private Short job; //职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师'
private LocalDate entrydate; //入职日期
private Integer deptId; //部门ID
private LocalDateTime createTime; //创建时间
private LocalDateTime updateTime; //修改时间
}
3.empper接口方法
package cn.vqqc.mapper;
import cn.vqqc.pojo.Emp;
import org.apache.ibatis.annotations.*;
import java.time.LocalDate;
import java.util.List;
@Mapper
public interface EmpMapper {
//根据ID删除数据
@Delete("delete from emp where id = #{id}")
public void delete(Integer id);
//public int delete(Integer id);
//新增员工
@Options(useGeneratedKeys = true, keyProperty = "id")
@Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time)" +
" values (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")
public void insert(Emp emp);
//更新员工
@Update("update emp set username = #{username}, name = #{name}, gender = #{gender}, image = #{image}," +
" job = #{job}, entrydate = #{entrydate}, dept_id = #{deptId},update_time = #{updateTime} where id = #{id}")
public void update(Emp emp);
//方案三: 开启mybatis的驼峰命名自动映射开关 --- a_cloumn ------> aColumn
//根据ID查询员工
@Select("select * from emp where id = #{id}")
public Emp getById(Integer id);
//方案一: 给字段起别名, 让别名与实体类属性一致
//@Select("select id, username, password, name, gender, image, job, entrydate, " +
// "dept_id deptId, create_time createTime, update_time updateTime from emp where id = #{id}")
//public Emp getById(Integer id);
//方案二: 通过@Results, @Result注解手动映射封装
//@Results({
// @Result(column = "dept_id", property = "deptId"),
// @Result(column = "create_time", property = "createTime"),
// @Result(column = "update_time", property = "updateTime")
//})
//@Select("select * from emp where id = #{id}")
//public Emp getById(Integer id);
//条件查询员工
//方式一
//@Select("select * from emp where name like '%${name}%' and gender = #{gender} and " +
// "entrydate between #{begin} and #{end} order by update_time desc ")
//public List<Emp> list(String name, Short gender, LocalDate begin , LocalDate end);
//方式二
// @Select("select * from emp where name like concat('%',#{name},'%') and gender = #{gender} and " +
// "entrydate between #{begin} and #{end} order by update_time desc ")
// public List<Emp> list(String name, Short gender, LocalDate begin , LocalDate end);
//动态条件查询
public List<Emp> list(String name, Short gender, LocalDate begin , LocalDate end);
//动态更新员工
public void update2(Emp emp);
//批量删除员工
public void deleteByIds(List<Integer> ids);
}
4.连接数据库配置
#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=1234
#配置mybatis的日志, 指定输出到控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#开启mybatis的驼峰命名自动映射开关 a_column ------> aCloumn
mybatis.configuration.map-underscore-to-camel-case=true
5.启动测试类
package cn.vqqc;
import cn.vqqc.mapper.EmpMapper;
import cn.vqqc.pojo.Emp;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
@SpringBootTest
class SpringbootMybatisCrudApplicationTests {
@Autowired
private EmpMapper empMapper;
//根据ID删除
@Test
public void testDelete(){
//int delete = empMapper.delete(16);
//System.out.println(delete);
empMapper.delete(17);
}
//新增员工
@Test
public void testInsert(){
//构造员工对象
Emp emp = new Emp();
emp.setUsername("Tom3");
emp.setName("汤姆3");
emp.setImage("1.jpg");
emp.setGender((short)1);
emp.setJob((short)1);
emp.setEntrydate(LocalDate.of(2000,1,1));
emp.setCreateTime(LocalDateTime.now());
emp.setUpdateTime(LocalDateTime.now());
emp.setDeptId(1);
//执行新增员工信息操作
empMapper.insert(emp);
System.out.println(emp.getId());
}
//更新员工
@Test
public void testUpdate(){
//构造员工对象
Emp emp = new Emp();
emp.setId(18);
emp.setUsername("Tom1");
emp.setName("汤姆1");
emp.setImage("1.jpg");
emp.setGender((short)1);
emp.setJob((short)1);
emp.setEntrydate(LocalDate.of(2000,1,1));
emp.setUpdateTime(LocalDateTime.now());
emp.setDeptId(1);
//执行更新员工操作
empMapper.update(emp);
}
//根据ID查询员工
@Test
public void testGetById(){
Emp emp = empMapper.getById(20);
System.out.println(emp);
}
//根据条件查询员工
@Test
public void testList(){
//List<Emp> empList = empMapper.list("张", (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
//List<Emp> empList = empMapper.list("张", null, null, null);
//List<Emp> empList = empMapper.list("张", (short)1, null, null);
//List<Emp> empList = empMapper.list(null, (short)1, null, null);
List<Emp> empList = empMapper.list(null, null, null, null);
System.out.println(empList);
}
//动态更新员工 - 更新ID为18的员工 username 更新为 Tom111, name更新为 汤姆111, gender更新为2
@Test
public void testUpdate2(){
//构造员工对象
Emp emp = new Emp();
emp.setId(19);
emp.setUsername("Tom222333");
// emp.setName("汤姆222");
// emp.setGender((short)1);
// emp.setUpdateTime(LocalDateTime.now());
//执行更新员工操作
empMapper.update2(emp);
}
//批量删除员工 - 13,14,15
@Test
public void testDeleteByIds(){
List<Integer> ids = Arrays.asList(13, 14, 15);
empMapper.deleteByIds(ids);
}
}
6.EmpMapper.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="cn.vqqc.mapper.EmpMapper">
<sql id="commonSelect">
select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time
from emp
</sql>
<!-- 动态更新员工-->
<update id="update2">
update emp
<set>
<if test="username != null">username = #{username},</if>
<if test="name != null">name = #{name},</if>
<if test="gender != null">gender = #{gender},</if>
<if test="image != null">image = #{image},</if>
<if test="job != null">job = #{job},</if>
<if test="entrydate != null">entrydate = #{entrydate},</if>
<if test="deptId != null">dept_id = #{deptId},</if>
<if test="updateTime != null">update_time = #{updateTime}</if>
</set>
where id = #{id}
</update>
<!--resultType: 单条记录封装的类型-->
<select id="list" resultType="cn.vqqc.pojo.Emp">
<include refid="commonSelect"/>
<where>
<if test="name != null">
name like concat('%', #{name}, '%')
</if>
<if test="gender != null">
and gender = #{gender}
</if>
<if test="begin != null and end != null">
and entrydate between #{begin} and #{end}
</if>
</where>
order by update_time desc
</select>
<!--批量删除员工 (18,19,20)-->
<!--
collection: 遍历的集合
item: 遍历出来的元素
separator: 分隔符
open: 遍历开始前拼接的SQL片段
close: 遍历结束后拼接的SQL片段
-->
<delete id="deleteByIds">
delete from emp where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
</mapper>
7.pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.vqqc</groupId>
<artifactId>springboot-mybatis-crud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-mybatis-crud</name>
<description>springboot-mybatis-crud</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
视频总结
01. Mybatis-基础操作-环境准备
https://www.bilibili.com/video/BV1m84y1w7Tb/?p=122
02. Mybatis-基础操作-删除
https://www.bilibili.com/video/BV1m84y1w7Tb/?p=123
03. Mybatis-基础操作-删除(预编译SQL)
https://www.bilibili.com/video/BV1m84y1w7Tb/?p=124
04. Mybatis-基础操作-新增
https://www.bilibili.com/video/BV1m84y1w7Tb/?p=125
05. Mybatis-基础操作-新增(主键返回)
https://www.bilibili.com/video/BV1m84y1w7Tb/?p=126
06. Mybatis-基础操作-更新
https://www.bilibili.com/video/BV1m84y1w7Tb/?p=127
07. Mybatis-基础操作-查询(根据ID查询)
https://www.bilibili.com/video/BV1m84y1w7Tb/?p=128
08. Mybatis-基础操作-查询(条件查询)
https://www.bilibili.com/video/BV1m84y1w7Tb/?p=129
09. Mybatis-XML映射文件
https://www.bilibili.com/video/BV1m84y1w7Tb/?p=130
10. Mybatis-动态SQL-if
https://www.bilibili.com/video/BV1m84y1w7Tb/?p=131
11. Mybatis-动态SQL-if-案例
https://www.bilibili.com/video/BV1m84y1w7Tb/?p=132
12. Mybatis-动态SQL-foreach
https://www.bilibili.com/video/BV1m84y1w7Tb/?p=133
13. Mybatis-动态SQL-sql&include
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容