1. Mybatis基础操作
1.准备
1. 创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok)
2. application.properties中引入数据库连接信息(复制过来即可)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.username=root
spring.datasource.password=1234
3. 准备数据库表 emp,及对应的实体类 Emp (实体类属性采用驼峰命名模式)
4. 准备Mapper接口 EmpMapper
日志输入
可以在application.properties中,打开mybatis的日志,并指定输出到控制台。
#指定mybatis输出日志的位置, 输出控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
开启日志之后,我们再次运行单元测试。可以看到在控制台中,输出了执行的SQL语句。
预编译SQL
两个优势:
- 性能更高
- 防止SQL注入
A. 性能更高: 预编译SQL,编译一次之后会将编译后的SQL语句缓存起来,后面再次执行这条insert语句时,SQL语句一样,不会再次编译。 只是输入的参数不同。
B. 防止SQL注入:将敏感字进行转义,安全。
SQL注入
SQL注入是通过操作输入来修改事先定义好的SQL语句,用以达到执行代码对服务器进行攻击的方法。
参数占位符
在Mybatis中提供的参数占位符有两种:${…}, #{…}。
1). #{…}
执行SQL时,会将#{…}替换为?,生成预编译SQL,会自动设置参数值。
使用时机:参数传递,都使用#{…}
2). ${…}
拼接SQL。直接将参数拼接在SQL语句中,存在SQL注入问题。
使用时机:如果对表名、列表进行动态设置时使用。
#与$的区别
- 都是mybatis中占位符 .
- #{…} , 被 ? 替代 ,生成 预编译SQL ,性能高,安全(防止SQL注入)
- ${…} , 拼接符号 ,性能不高,不安全
注意事项:
在项目开发中,建议使用#{…},生成预编译SQL,防止SQL注入安全。
==>基本操作(增删改查)
1. 新增(insert)
1). SQL
insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) values ('linghuchong','令狐冲',1,'1.jpg',2,'2012-10-09',2,'2022-10-01 10:00:00','2022-10-01 10:00:00');
2). 接口方法
@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);
#{…} 里面写的名称是对象的属性。
3). 测试
@Test
public void testInsert(){
Emp emp = new Emp(null,"songyuanqiao2",null,"宋远桥2",(short)1,"1.jpg",(short)2, LocalDate.of(2012,10,10),2,LocalDateTime.now(),LocalDateTime.now());
empMapper.insert(emp);
System.out.println(emp.getId());
}
主键返回
- 含义:在数据添加成功后,需要获取插入数据库数据的主键。如:添加菜品口味。
@Options(keyProperty = "id", useGeneratedKeys = true)//主键返回
@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);
2. 删除(delete)
1).对应的SQL:
delete from emp where id = 17;
2).接口方法
@Mapper
public interface EmpMapper {
@Delete("delete from emp where id = #{id}")
public void delete(Integer id);
}
3).单元测试
可以直接在单元测试类中通过 @Autowired 注解 EmpMapper接口。 然后就可以直接调用其delete方法传递参数进行测试
@SpringBootTest
class SpringbootMybatisQuickstart2ApplicationTests {
@Autowired
private EmpMapper empMapper;
@Test
public void testDel(){
empMapper.delete(15);
}
}
3. 修改(update)
1). SQL
update emp set username = 'linghushaoxia', name = '令狐少侠', gender = 1 , image = '1.jpg' , job = 2, entrydate = '2012-01-01', dept_id = 2, update_time = '2022-10-01 12:12:12' where id = 18;
2). 接口方法
@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);
3). 单元测试
@Test
public void testUpdate(){
Emp emp = new Emp(19,"songdaxia",null,"宋大侠2",(short)1,"2.jpg",(short)2, LocalDate.of(2012,1,1),2,null,LocalDateTime.now());
empMapper.update(emp);
}
4. 查询(getById)
1.1 根据ID查询
1). SQL
select * from emp where id = 19;
2). 接口方法
@Select("select * from emp where id = #{id}")
public Emp getById(Integer id);
3). 单元测试
@Test
public void testGetById(){
Emp emp = empMapper.getById(1);
System.out.println(emp);
}
数据封装
如果pojo实体类属性名 和 数据库表查询返回的字段名不一致,无法自动封装, 如何解决?
解决方案:
1). 起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样。
@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);
2). 手动结果映射:通过 @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);
3). 开启驼峰命名(推荐):如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射。
#开启驼峰命名自动映射,即从经典数据库列名 a_column 映射到经典 Java 属性名 aColumn。
mybatis.configuration.map-underscore-to-camel-case=true
注意事项: 要使用驼峰命名前提是 实体类的属性 与 数据库表中的字段名严格遵守驼峰命名。
1.2 条件查询
- SQL:
select * from emp where name like '%张%' and gender = 1 and entrydate between '2010-01-01' and '2020-01-01' order by update_time desc;
- 接口方法:
方式一:
@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(@Param("name")String name, @Param("gender")Short gender , @Param("begin")LocalDate begin ,@Param("end")LocalDate end);
这种方式使用 $ 进行字符串拼接,这种方式呢,由于是字符串拼接,并不是预编译的形式,所以效率不高、且存在sql注入风险。
方式二:
@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(@Param("name")String name, @Param("gender")Short gender , @Param("begin")LocalDate begin ,@Param("end")LocalDate end);
这种方式,生成的SQL都是预编译的SQL语句。 性能高、安全。 推荐方式二
2. Mybatis动态SQL
2.1 XML映射文件(取代注解书写sql)
使用Mybatis的注解,主要是来完成一些简单的增删改查功能。
- 简单的SQL语句用注解实现
- 复杂的SQL语句用xml / 动态sql / 多表查询
SQL映射配置文件的书写规范:
-
XML映射文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包下。(同包同名)
-
XML映射文件的namespace属性为Mapper接口全限定名一致。
-
XML映射文件中sql语句的id与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=" 接口全限定名 ">
<select id="接口方法名" resultType=" 返回值类型 ">
<!-- sql语句 -->
</select>
</mapper>
<select>标签的resultType属性,指的是查询返回的单条记录所封装的类型。
1. if标签
:用于判断条件是否成立,使用test属性进行条件判断,如果条件为true,则拼接SQL。
条件查询案例:
- EmpMapper接口方法
public List<Emp> list(String name, Short gender , LocalDate begin ,LocalDate end);
- EmpMapper.xml
<select id="list" resultType="com.itheima.pojo.Emp">
select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp
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>
order by update_time desc
</select>
-
测试代码
@Test public void testList(){ List<Emp> empList = empMapper.list(null, (short)1, null,null); for (Emp emp : empList) { System.out.println(emp); } }
2.where标签
:where 元素只会在子元素有内容的情况下才插入where子句。而且会自动去除子句的开头的AND 或OR。
通过标签改造上述功能, 改造后的配置为:
<select id="list" resultType="com.itheima.pojo.Emp">
select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp
<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>
3. set标签
动态的在行首插入set关键字,会删掉额外的逗号(主要用在update语句中)
修改案例:
-
接口方法
public void update(Emp emp);
-
EmpMapper.xml
<update id="update">
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>
测试
@Test
public void testUpdate2(){
Emp emp = new Emp();
emp.setId(19);
emp.setUsername("syq");
empMapper.update(emp);
}
4. foreach标签
用于在SQL语句中根据集合数据进行迭代操作。它常用于批量插入、更新或删除数据库记录。
删除案例:
1). SQL语句
delete from emp where id in (1,2,3);
2). 接口方法
//批量删除
public void deleteByIds(List<Integer> ids);
3). XML映射文件
<delete id="deleteByIds">
delete from emp where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
foreach属性介绍:
collection:集合名称
item:集合遍历出来的元素/项
separator:每一次遍历使用的分隔符
open:遍历开始前拼接的片段
close:遍历结束后拼接的片段
2.4 sql/include标签
标签含义:
sql:定义可重用的 SQL 片段。
include:通过属性refid,指定包含的sql片段。
● 案例问题分析:
在xml映射文件中配置的SQL,有时可能会存在很多重复的片段,此时就会存在很多冗余的代码。如下图这样:
我们可以考虑对重复的代码片段进行抽取,将其通过 标签封装到一个SQL片段 。 如下:
<sql id="commonSelect">
select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp
</sql>
然后在原来抽取的地方进行引用,通过 include 标签。如下: