学习MyBatis必知必会(7)~注解开发、动态SQL

简介: 学习MyBatis必知必会(7)~注解开发、动态SQL

一、MyBatis的注解开发

  • 开发中推荐是使用xml文件配置

1、配置映射关系【使用注解的方式】:

<!-- 全局的配置文件 --> 
<configuration>
   <!-- 2、关联映射文件/ 关联Mapper接口  --> 
  <mappers>
    <!--  <mapper resource="com/shan/hello/mapper/UserMapper.xml"/>-->
    <mapper class="com.shan.hello.mapper.UserMapper"/>
  </mappers>
  </configuration>

2、通过注解,把sql和映射写到Mapper接口:

public interface UserMapper {
  @Insert("insert into t_user (name, salary) values (#{name}, #{salary});")
  @Options(useGeneratedKeys = true,keyProperty = "id")
  void save(User user);
  @Delete("delete from t_user where id = #{id};")
  void delete(Long id);
  @Update("update t_user set name = #{name}, salary = #{salary} where id = #{id};")
  void update(User user);
//  void update(User user, Long id);//错误:myBatis默认只能传递一个参数
  @Select("select id u_id, name as u_name, salary u_salary from t_user where id = #{id}")
  @Results(id="BaseResultMap", value= {
      @Result(column = "u_id",property = "id"),
      @Result(column = "u_name",property = "name"),
      @Result(column = "u_salary",property = "salary")
  })
  User get(Long id);
  @Select("select id u_id, name as u_name, salary u_salary from t_user")
  @ResultMap("BaseResultMap")
  List<User> getListAll();
}

3、测试(这里以测试查询为例):

/* 测试查询 */
  @Test
  public void testGet() throws IOException {
    SqlSession session = MyBatisUtil.getSession();
    UserMapper userMapper = session.getMapper(UserMapper.class);
    User user = userMapper.get(2L);
    System.out.println(user);
    //5、关闭资源
    session.close();
  }


二、动态SQL 【类似JSTL(java标准标签库)语法】

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach
  • 其他(bind,sql,include)

1、if 举例:

<!-- 映射文件 -->
  <select id="select" resultType="Employee">
    select * from employee 
    <if test="minSalary != null">
      where salary >= #{minSalary}
    </if>
  </select>
  • 细节:在xml中 小于符合不能直接输入 < , 会被当做标签的开始标志,需要使用转义符号 &lt;
  • 防止第一个查询条件是null,加上 where 1=1,然后其他查询条件接着and 写。


2、choose (when, otherwise) 举例:

<!-- 映射文件 -->
 <select id="select" resultType="Employee">
      select * from employee where 1=1
    <if test="minSalary != null">
      and salary >= #{minSalary}
    </if>
    <choose>
      <when test="deptId > 0">and deptId = #{deptId}</when>
      <otherwise>and deptId is not null</otherwise>
    </choose>
  </select>


3-1、trim (where, set)- where 举例:

  • 解决sql拼接查询条件时第一个条件为null,而加上 where 1=1,导致不能进行索引查询,影响性能。
  • where 元素:判断查询条件是否有where关键字,若没有,则第一个查询条件之前要插入 where
    若发现查询条件是以and/or开头,则会把第一个查询条件前的and/or 替换成 where
<!-- 映射文件 -->
  <select id="select" resultType="Employee">
      select * from employee 
  <where>
     <if test="minSalary != null">
          and salary >= #{minSalary}
        </if>
      <if test="maxSalary != null">
        and salary &lt;= #{maxSalary}
      </if>
      <choose>
        <when test="deptId > 0">and deptId = #{deptId}</when>
        <otherwise>and deptId is not null</otherwise>
        </choose>
  </where>
  </select>

3-2、trim (where, set)-set 举例:

  • 和where 类似,动态去掉最后一个逗号
<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>

3-3、trim (where, set)-trim :

<trim prefix="" prefixOverrides="" suffix="" suffixOverrides="">
  <!--trim 包含的动态 SQL-->
</trim>

prefix – 在这个字符串之前插入 prefix 属性值。

prefixOverrides – 并且字符串的内容以 prefixOverrides 中的内容开头(可以包含管道符号),那么使用 prefix 属性值替换内容的开头。

suffix – 在这个字符串之后插入 suffix 属性值。

suffixOverrides –并且字符串的内容以 suffixOverrides 中的内容结尾(可以包含管道符号),那么使用 suffix 属性值替换内容的结尾。

  • 使用 where 等价于: 注意:此时 AND 后面有一个空格。
  • 使用 set 等价于:


4、foreach 举例1:

/* Mapper接口 */
void batchDelete(@Param("ids")List<Long> ids);
<!-- 映射文件 -->
 <!-- 
    foreach 元素: collection属性:表示要迭代的集合或数组【的类型,若是通过Parm注解,可以直接写上Map中的key,而不用填写类型】
            open属性:在集合迭代之前,要拼接的符号   close 属性:在集合迭代之后要拼接的符号
            separator属性:迭代的元素之间的分割符号
            item属性:每个被迭代的元素
            index属性:迭代的索引
   -->
  <delete id="batchDelete">
    delete from employee where id in
    <foreach collection="ids" open="(" close=")" separator="," item="id">
      #{id}
    </foreach>
  </delete>

■ foreach 举例2:

/* Mapper接口 */
void batchSave(@Param("emps")List<Employee>emps);
  <!-- 映射文件 -->
  <insert id="batchSave">
    insert into employee (name, sn, salary) values 
    <foreach collection="emps" separator="," item="e">
      (#{e.name}, #{e.sn}, #{e.salary})
    </foreach>
  </insert>


5、其他(bind,sql,include) 举例-高级分页查询:

■ sql,include 的例子:

<!-- 映射文件 -->
<mapper namespace="com.shan.hello.mapper.EmployeeMapper">
  <sql id="base_where">
    <where>
      <if test="keyword != null">
        <!--and name like #{%name%}; 要使用字符串函数concat进行拼接呀 -->
        <!-- and name like concat('%', #{name}, '%') or sn like concat('%', #{sn},'%'); qo查询对象,也没有属性name,sn呀 -->
        and (name like concat('%', #{keyword}, '%') or sn like concat('%', #{keyword}, '%'))
      </if>
      <if test="minSalary != null">
        and salary >= #{minSalary}
      </if>
      <if test="maxSalary != null">
        and salary &lt;= #{maxSalary}
      </if>
      <if test="deptId > 0">
        and deptId = #{deptId}
      </if>
    </where>
  </sql>
  <select id="queryForList" resultType="Employee">
    select id, name, sn, salary from employee
    <include refid="base_where"/>
  </select>
  <select id="queryForCount" resultType="int">
    select count(id) from employee
    <include refid="base_where"/>
  </select>
</mapper>

■ bind(跟concat一样是用于拼接字符串) 的例子:

<if test="keyword != null">
  <!--and name like #{%name%}; 要使用字符串函数concat进行拼接呀 -->
  <!-- and name like concat('%', #{name}, '%') or sn like concat('%', #{sn},'%'); qo查询对象,也没有属性name,sn呀 -->
  <!-- and (name like concat('%', #{keyword}, '%') or sn like concat('%', #{keyword}, '%')) -->
  <bind name="keywordLike" value="'%' + keyword + '%'"/>
      and (name like #{keywordLike} or sn like #{keywordLike})
</if>
目录
相关文章
|
2月前
|
SQL 关系型数据库 MySQL
【MySQL】根据binlog日志获取回滚sql的一个开发思路
【MySQL】根据binlog日志获取回滚sql的一个开发思路
|
7天前
|
SQL XML Java
mybatis复习03,动态SQL,if,choose,where,set,trim标签及foreach标签的用法
文章介绍了MyBatis中动态SQL的用法,包括if、choose、where、set和trim标签,以及foreach标签的详细使用。通过实际代码示例,展示了如何根据条件动态构建查询、更新和批量插入操作的SQL语句。
mybatis复习03,动态SQL,if,choose,where,set,trim标签及foreach标签的用法
|
9天前
|
Java 关系型数据库 数据库连接
mybatis-plus学习
MyBatis-Plus ,MyBatis 最佳搭档,只做增强不做改变,为简化开发、提高效率而生。
25 5
|
11天前
|
SQL 安全 Go
SQL注入不可怕,XSS也不难防!Python Web安全进阶教程,让你安心做开发!
在Web开发中,安全至关重要,尤其要警惕SQL注入和XSS攻击。SQL注入通过在数据库查询中插入恶意代码来窃取或篡改数据,而XSS攻击则通过注入恶意脚本来窃取用户敏感信息。本文将带你深入了解这两种威胁,并提供Python实战技巧,包括使用参数化查询和ORM框架防御SQL注入,以及利用模板引擎自动转义和内容安全策略(CSP)防范XSS攻击。通过掌握这些方法,你将能够更加自信地应对Web安全挑战,确保应用程序的安全性。
39 3
|
1月前
|
SQL XML Java
mybatis :sqlmapconfig.xml配置 ++++Mapper XML 文件(sql/insert/delete/update/select)(增删改查)用法
当然,这些仅是MyBatis功能的初步介绍。MyBatis还提供了高级特性,如动态SQL、类型处理器、插件等,可以进一步提供对数据库交互的强大支持和灵活性。希望上述内容对您理解MyBatis的基本操作有所帮助。在实际使用中,您可能还需要根据具体的业务要求调整和优化SQL语句和配置。
30 1
|
2月前
|
SQL NoSQL 数据库
开发效率与灵活性:SQL vs NoSQL
【8月更文第24天】随着大数据和实时应用的兴起,数据库技术也在不断发展以适应新的需求。传统的SQL(结构化查询语言)数据库因其成熟的数据管理机制而被广泛使用,而NoSQL(Not Only SQL)数据库则以其灵活性和扩展性赢得了众多开发者的青睐。本文将从开发者的视角出发,探讨这两种数据库类型的优缺点,并通过具体的代码示例来说明它们在实际开发中的应用。
50 1
|
25天前
|
SQL 分布式计算 大数据
大数据开发SQL代码编码原则和规范
这段SQL编码原则强调代码的功能完整性、清晰度、执行效率及可读性,通过统一关键词大小写、缩进量以及禁止使用模糊操作如select *等手段提升代码质量。此外,SQL编码规范还详细规定了代码头部信息、字段与子句排列、运算符前后间隔、CASE语句编写、查询嵌套、表别名定义以及SQL注释的具体要求,确保代码的一致性和维护性。
26 0
|
2月前
|
SQL 关系型数据库 MySQL
SQL Server、MySQL、PostgreSQL:主流数据库SQL语法异同比较——深入探讨数据类型、分页查询、表创建与数据插入、函数和索引等关键语法差异,为跨数据库开发提供实用指导
【8月更文挑战第31天】SQL Server、MySQL和PostgreSQL是当今最流行的关系型数据库管理系统,均使用SQL作为查询语言,但在语法和功能实现上存在差异。本文将比较它们在数据类型、分页查询、创建和插入数据以及函数和索引等方面的异同,帮助开发者更好地理解和使用这些数据库。尽管它们共用SQL语言,但每个系统都有独特的语法规则,了解这些差异有助于提升开发效率和项目成功率。
131 0
|
2月前
|
SQL Java 数据库连接
后端框架的学习----mybatis框架(7、使用注解开发)
这篇文章讲述了如何使用MyBatis框架的注解方式进行开发,包括在接口上使用注解定义SQL语句,并通过动态代理实现对数据库的增删改查操作,同时强调了接口需要在核心配置文件中注册绑定。
|
19天前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
下一篇
无影云桌面