快速入门操作Mybatis
接下来的Mybatis操作数据库增删改查都会直接举例说明用法
删除
mapper接口中编写删除操作的SQL语句
//使用#{key}方式获取方法中的参数值
@Delete("delete from emp where id = #{id}")
public void delete(Integer id);
此处的 #{id} 可以使SQL语句中的参数不再固定,这样可以方法传参给SQL语句
在单元测试类中进行测试
//从Spring的IOC容器中,获取类型是EmpMapper的对象并注入
@Autowired
private EmpMapper empMapper;
@Test
public void testDel(){
//调用删除方法
empMapper.delete(16);
}
参数占位符
在Mybatis中提供的参数占位符有两种:${...} 、#{...}
-
#{...}
-
执行SQL时,会将#{…}替换为?,生成预编译SQL,会自动设置参数值
-
使用时机:参数传递,都使用#{…}
-
-
${...}
-
拼接SQL。直接将参数拼接在SQL语句中,存在SQL注入问题
-
使用时机:如果对表名、列表进行动态设置时使用
-
建议使用 #{ } ,预编译SQL,防止SQL注入,更安全
新增
mapper接口中编写新增SQL语句
@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);//#{ }中的值是实体类对象的属性名
测试类中创建员工对象,调用添加方法即可。
主键返回
想要在添加数据之后获取主键,添加注解即可
//会自动将生成的主键值,赋值给emp对象的id属性
@Options(useGeneratedKeys = true,keyProperty = "id")
更新
@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);
查询
@Select("select * from emp where id=#{id}")
public Emp getById(Integer id);
此时注意,当字段名和实体类属性名不一致时,数据不会被自动封装,例如 cardId 和 card_id。
一致时,mybatis会自动封装。
解决问题其实很简单,可以给字段名起别名和手动映射,但都复杂,可以在 application.properties中添加:
mybatis.configuration.map-underscore-to-camel-case=true
即可开启驼峰命名自动封装数据。
条件查询
以下是模糊姓名查询
@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 List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
}
其中的concat是拼接的函数,解决了后面的sql注入风险
Mybatis的XML配置文件
使用Mybatis的注解方式,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句,也就是将SQL语句写在XML配置文件中。
在Mybatis中使用XML映射文件方式开发,需要符合一定的规范:
-
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"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
Mybatis动态SQL
前言:在企业平常开发中,有多个条件查询,如果按照以前的逻辑必须要把所有条件填写完才行,如果有字段没有填写,那么字段的参数为null。
SQL语句会随着用户的输入或外部条件的变化而变化,我们称为:动态SQL。
动态SQL-if
<if>
:用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL。
<if test="条件表达式">
要拼接的sql语句
</if>
举例说明:
<select id="list" resultType="com.itheima.pojo.Emp">
select * 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>
其中经过if判断,如果为空则不拼接当前sql语句,若不为空则一直拼接到底。
注意: 会出问题,如果第一个条件为空,第二个不为空则会直接拼接第二条语句,包含and,则会导致整个SQL语句以and开头,直接语法错误,想解决这个办法,可以用 <where> </where> 解决。在SQL的update语句中也会出现类似错误,使用 <set> </set> 即可
动态SQL-foreach
可以使用<foreach></foreach>遍历方法中传递的集合
<foreach collection="集合名称" item="集合遍历出来的元素/项" separator="每一次遍历使用的分隔符"
open="遍历开始前拼接的片段" close="遍历结束后拼接的片段">
</foreach>
举例说明:
<mapper namespace="com.itheima.mapper.EmpMapper">
<!--删除操作-->
<delete id="deleteByIds">
delete from emp where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
</mapper>
动态SQL-sql&include
可以提高代码简洁性,去除冗余重复代码。
我们可以对重复的代码片段进行抽取,将其通过<sql>
标签封装到一个SQL片段,然后再通过<include>
标签进行引用。
-
<sql>
:定义可重用的SQL片段 -
<include>
:通过属性refid,指定包含的SQL片段
举例说明:
sql抽取重复代码
<sql id="commonSelect">
select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp
</sql>
通过<include>标签在原代码处引用。
<select id="list" resultType="com.itheima.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>