怎么做网站流量统计分析,北京装修设计师哪里找,做招聘海报的网站,wordpress 充值记录Mybatis#xff08;2#xff09; 1 Mybatis基础操作1.1 需求和准备工作1.2 删除员工日志输入参数占位符 1.3 新增员工1.4 修改员工信息1.5 查询员工1.5.1 根据ID查询数据封装 1.5.3 条件查询 2 XML配置文件规范3 MyBatis动态SQL3.1 什么是动态SQL3.2 动态SQL-if更新员工 3.3 … Mybatis2 1 Mybatis基础操作1.1 需求和准备工作1.2 删除员工日志输入参数占位符 1.3 新增员工1.4 修改员工信息1.5 查询员工1.5.1 根据ID查询数据封装 1.5.3 条件查询 2 XML配置文件规范3 MyBatis动态SQL3.1 什么是动态SQL3.2 动态SQL-if更新员工 3.3 动态SQL-foreach3.4 动态SQL-sqlinclude 这部分真的麻烦 建议看视频 黑马程序员 JavaWeb(2023年) P130
1 Mybatis基础操作
1.1 需求和准备工作
对员工管理的需求开发。 查询 根据主键ID查询条件查询 新增 更新 删除 根据主键ID删除根据主键ID批量删除
实施前的准备工作
准备数据库表创建一个新的springboot工程选择引入对应的起步依赖mybatis、mysql驱动、lombokapplication.properties中引入数据库连接信息创建对应的实体类 Emp实体类属性采用驼峰命名准备Mapper接口 EmpMapper
连接数据库后进行数据准备 一下就在mybatis这个database中进行的
-- 部门管理
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());创建一个新的springboot工程选择引入对应的起步依赖mybatis、mysql驱动、lombok application.properties中引入数据库连接信息
#驱动类名称
spring.datasource.driver-class-namecom.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.urljdbc:mysql://localhost:3306/mybatis
#连接数据库的用户名
spring.datasource.usernameroot
#连接数据库的密码
spring.datasource.password你的密码创建对应的实体类Emp实体类属性采用驼峰命名
package com.itheima.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.time.LocalDateTime;Data
NoArgsConstructor
AllArgsConstructor
public class Emp { //复制一下全类名 copy referenceprivate Integer id; //IDprivate String username; //用户名private String password; //密码private String name; //姓名private Short gender; //性别, 1 男, 2 女private String image; //图像urlprivate Short job; //职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师private LocalDate entrydate; //入职日期private Integer deptId; //部门IDprivate LocalDateTime createTime; //创建时间private LocalDateTime updateTime; //修改时间
}
准备Mapper接口EmpMapper
/*Mapper注解表示当前接口为mybatis中的Mapper接口程序运行时会自动创建接口的实现类对象(代理对象)并交给Spring的IOC容器管理
*/
Mapper
public interface EmpMapper {}目录结构 Unable to resolve table ‘emp’
这样的报错解决方案 检查Data Sources and Drivers中的URL 是否与 数据库连接的url spring.datasource.urljdbc:mysql://localhost:3306/mybatis 相匹配,数据库是否连接
1.2 删除员工
功能根据主键删除数据
日志输入
在Mybatis当中我们可以借助日志查看到sql语句的执行、执行传递的参数以及执行结果。具体操作如下 打开application.properties文件 开启mybatis的日志并指定输出到控制台
#指定mybatis输出日志的位置, 输出控制台
mybatis.configuration.log-implorg.apache.ibatis.logging.stdout.StdOutImpl参数占位符
在Mybatis中提供的参数占位符有两种${…} 、#{…} #{…} 执行SQL时会将#{…}替换为?生成预编译SQL会自动设置参数值使用时机参数传递都使用#{…} ${…} 拼接SQL。直接将参数拼接在SQL语句中存在SQL注入问题使用时机如果对表名、列表进行动态设置时使用 注意事项在项目开发中建议使用#{…}生成预编译SQL防止SQL注入安全。 在P124 老师演示的SQL注入操作,无法登录,他只是演示一下,他的jar跟我们的不一样,无法使用
1.3 新增员工
#开启mybatis的驼峰命名自动映射开关 a_column ------ aCloumn
mybatis.configuration.map-underscore-to-camel-casetrue//会自动将生成的主键值赋值给emp对象的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}))1.4 修改员工信息
Mapper
public interface EmpMapper {/*** 根据id修改员工信息* param 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);}SpringBootTest
class SpringbootMybatisCrudApplicationTests {Autowiredprivate EmpMapper empMapper;Testpublic void testUpdate(){//要修改的员工信息Emp emp new Emp();emp.setId(23);emp.setUsername(songdaxia);emp.setPassword(null);emp.setName(老宋);emp.setImage(2.jpg);emp.setGender((short)1);emp.setJob((short)2);emp.setEntrydate(LocalDate.of(2012,1,1));emp.setCreateTime(null);emp.setUpdateTime(LocalDateTime.now());emp.setDeptId(2);//调用方法修改员工数据empMapper.update(emp);}
}1.5 查询员工
1.5.1 根据ID查询
Mapper
public interface EmpMapper {Select(select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id#{id})public Emp getById(Integer id);
}SpringBootTest
class SpringbootMybatisCrudApplicationTests {Autowiredprivate EmpMapper empMapper;Testpublic void testGetById(){Emp emp empMapper.getById(1);System.out.println(emp);}
}数据封装 实体类属性名和数据库表查询返回的字段名一致mybatis会自动封装。如果实体类属性名和数据库表查询返回的字段名不一致不能自动封装。(deptIdcreateTimeupdateTime这几个字段是没有值的,而数据库中是有对应的字段值) 解决方案
起别名结果映射开启驼峰命名
Select(select id, username, password, name, gender, image, job, entrydate, dept_id AS deptId, create_time AS createTime, update_time AS updateTime from emp where id#{id})
public Emp getById(Integer id);Results({Result(column dept_id, property deptId),Result(column create_time, property createTime),Result(column update_time, property updateTime)})
Select(select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id#{id})
public Emp getById(Integer id);
开启驼峰命名(推荐)如果字段名与属性名符合驼峰命名规则mybatis会自动通过驼峰命名规则映射 驼峰命名规则 abc_xyz abcXyz 表中字段名abc_xyz类中属性名abcXyz # 在application.properties中添加
mybatis.configuration.map-underscore-to-camel-casetrue要使用驼峰命名前提是 实体类的属性 与 数据库表中的字段名严格遵守驼峰命名。 1.5.3 条件查询
方式一: 模糊查询使用${…}进行字符串拼接这种方式呢由于是字符串拼接并不是预编译的形式所以效率不高、且存在sql注入风险。
/*** 条件查询员工* param name 员工姓名* param gender 员工性别*/
Select(select * from emp where name like %${name}% and gender #{gender} and entrydate between #{begin} and #{end} order by update_time desc)
public ListEmp list(String name, Short gender, LocalDate begin, LocalDate end);//测试根据条件查询员工Testpublic void testGetEmpByCondition() {ListEmp empListempMapper.list(张,(short) 1,LocalDate.of(2010,1,1),LocalDate.of(2020,1,1));System.out.println(empList);}方式二(解决SQL注入风险)
使用MySQL提供的字符串拼接函数concat(‘%’ , ‘关键字’ , ‘%’)
Mapper
public interface EmpMapper {Select(select * from emp where name like concat(%,#{name},%) and gender #{gender} and entrydate between #{begin} and #{end} order by update_time desc)public ListEmp list(String name, Short gender, LocalDate begin, LocalDate end);}2 XML配置文件规范
使用Mybatis的注解方式主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能建议使用XML来配置映射语句也就是将SQL语句写在XML配置文件中。
在Mybatis中使用XML映射文件方式开发需要符合一定的规范 XML映射文件的名称与Mapper接口名称一致并且将XML映射文件和Mapper接口放置在相同包下同包同名 XML映射文件的namespace属性为Mapper接口全限定名一致 XML映射文件中sql语句的id与Mapper接口中的方法名一致并保持返回类型一致。 去官网看入门https://mybatis.net.cn/getting-started.html 编写XML映射文件 xml映射文件中的dtd约束直接从mybatis官网复制即可 ?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttps://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespace/mapper配置XML映射文件的namespace属性为Mapper接口全限定名
配置XML映射文件中sql语句的id与Mapper接口中的方法名一致并保持返回类型一致
?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttps://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.itheima.mapper.EmpMapper!--查询操作--select idlist resultTypecom.itheima.pojo.Empselect * from empwhere name like concat(%,#{name},%)and gender #{gender}and entrydate between #{begin} and #{end}order by update_time desc/select
/mapperMybatisX是一款基于IDEA的快速开发Mybatis的插件为效率而生。 **结论**使用Mybatis的注解主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能建议使用XML来配置映射语句。
3 MyBatis动态SQL
3.1 什么是动态SQL
在页面原型中列表上方的条件是动态的是可以不传递的也可以只传递其中的1个或者2个或者全部。
SQL语句会随着用户的输入或外部条件的变化而变化我们称为动态SQL。 在Mybatis中提供了很多实现动态SQL的标签我们学习Mybatis中的动态SQL就是掌握这些动态SQL标签。 3.2 动态SQL-if
if用于判断条件是否成立。使用test属性进行条件判断如果条件为true则拼接SQL。
if test条件表达式要拼接的sql语句
/if接下来我们就通过if标签来改造之前条件查询的案例。
示例把SQL语句改造为动态SQL方式
原有的SQL语句
select idlist resultTypecom.itheima.pojo.Empselect * from empwhere name like concat(%,#{name},%)and gender #{gender}and entrydate between #{begin} and #{end}order by update_time desc
/select动态SQL语句
select idlist resultTypecom.itheima.pojo.Empselect * from empwhereif testname ! nullname like concat(%,#{name},%)/ifif testgender ! nulland gender #{gender}/ifif testbegin ! null and end ! nulland entrydate between #{begin} and #{end}/iforder by update_time desc
/select使用where标签代替SQL语句中的where关键字
where只会在子元素有内容的情况下才插入where子句而且会自动去除子句的开头的AND或OR
select idlist resultTypecom.itheima.pojo.Empselect * from empwhere!-- if做为where标签的子元素 --if testname ! nulland name like concat(%,#{name},%)/ifif testgender ! nulland gender #{gender}/ifif testbegin ! null and end ! nulland entrydate between #{begin} and #{end}/if/whereorder by update_time desc
/select更新员工
案例完善更新员工功能修改为动态更新员工数据信息
动态更新员工信息如果更新时传递有值则更新如果更新时没有传递值则不更新解决方案动态SQL
修改Mapper接口
Mapper
public interface EmpMapper {//删除Update注解编写的SQL语句//update操作的SQL语句编写在Mapper映射文件中public void update(Emp emp);
}修改Mapper映射文件
?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttps://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.itheima.mapper.EmpMapper!--更新操作--update idupdateupdate empsetif testusername ! nullusername#{username},/ifif testname ! nullname#{name},/ifif testgender ! nullgender#{gender},/ifif testimage ! nullimage#{image},/ifif testjob ! nulljob#{job},/ifif testentrydate ! nullentrydate#{entrydate},/ifif testdeptId ! nulldept_id#{deptId},/ifif testupdateTime ! nullupdate_time#{updateTime}/ifwhere id#{id}/update/mapper小结 if 用于判断条件是否成立如果条件为true则拼接SQL 形式 if testname ! null … /ifwhere where元素只会在子元素有内容的情况下才插入where子句而且会自动去除子句的开头的AND或OR set 动态地在行首插入 SET 关键字并会删掉额外的逗号。用在update语句中
3.3 动态SQL-foreach
案例员工删除功能既支持删除单条记录又支持批量删除 !--批量删除员工 --!--collection: 遍历的集合item: 遍历出来的元素separator: 分隔符open: 遍历开始前拼接的SQL片段close: 遍历结束后拼接的SQL片段--SQL语句
delete from emp where id in (1,2,3);Mapper接口
Mapper
public interface EmpMapper {//批量删除public void deleteByIds(ListInteger ids);
}XML映射文件
使用foreach遍历deleteByIds方法中传递的参数ids集合
foreach collection集合名称 item集合遍历出来的元素/项 separator每一次遍历使用的分隔符 open遍历开始前拼接的片段 close遍历结束后拼接的片段
/foreach?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttps://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.itheima.mapper.EmpMapper!--删除操作--delete iddeleteByIdsdelete from emp where id inforeach collectionids itemid separator, open( close)#{id}/foreach/delete
/mapper 3.4 动态SQL-sqlinclude
问题分析
在xml映射文件中配置的SQL有时可能会存在很多重复的片段此时就会存在很多冗余的代码
我们可以对重复的代码片段进行抽取将其通过sql标签封装到一个SQL片段然后再通过include标签进行引用。 sql定义可重用的SQL片段 include通过属性refid指定包含的SQL片段 SQL片段 抽取重复的代码
sql idcommonSelectselect id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp
/sql然后通过include 标签在原来抽取的地方进行引用。操作如下
select idlist resultTypecom.itheima.pojo.Empinclude refidcommonSelect/whereif testname ! nullname like concat(%,#{name},%)/ifif testgender ! nulland gender #{gender}/ifif testbegin ! null and end ! nulland entrydate between #{begin} and #{end}/if/whereorder by update_time desc
/select