JavaEE简单示例——动态SQL的<trim>属性

文章介绍了MyBatis中trim标签的使用,该标签允许自定义要添加或删除的SQL关键字,以适应更复杂的动态SQL构建。通过示例展示了如何在SQL映射文件中利用trim标签配合if标签进行条件判断,动态添加或移除SQL语句的前缀和后缀,从而实现灵活的查询和更新操作。

简单介绍:

在之前我们介绍过使用<where>和<set>可以帮我们动态的添加和删除一些关键字,但是这些只能操作特定的关键字,比如where和set,但是有一些时候我们需要操作的关键字并不是这些常见的关键字,而是一些没有标签进行直接操作的一些不常用的关键字,这时候如果想要删除或者添加这些关键字就要使用另一个标签<trim>标签,这个标签可以自定义我们要删除或者添加的关键字。

简单使用:

<select id="唯一标识" resultType="结果集封装的实体类" >

        select * from student

        <trim prefix="要添加的前缀关键字" suffixOverrides="要删除的后缀关键字">

                <if test="判断条件">

                        and 要拼接的SQL语句

                </if>

                <if test="判断条件">

                        and 要拼接的SQL语句

                </if>

        </trim>

</select>

<trim>标签有四个属性:

prefix:指定SQL语句增加的前缀

prefixOverrides:指定SQL语句中要去掉的前缀字符串

suffix:指定给SQL语句增加的后缀

suffixOverrides:指定SQL语句中要去掉的后缀字符串

代码实现:

SQL映射文件:

<?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="Mappers.dynamicSql">
  <select id="selectByIdOrName" parameterType="student" resultType="student">
    select * from student where 1=1
#                             当id的值不等于null并且id的值不是空字符的时候,就会拼接这个SQL语句
        <if test="id != null and id != ''">
          and id = #{id}
        </if>
#                             当name的值不等于null的时候并且name的值不是空字符串的时候,就会拼接这个SQL语句
        <if test="name != null and name != ''">
#                             注意这个地方是使用了一个concat函数将模糊匹配的百分号和参数进行拼接,在使用的时候注意这个地方不要写错
          and name like concat ('%',#{name},'%')
        </if>
  </select>
    <select id="selectAll" resultType="student">
        select * from student;
    </select>
<!--    动态SQL中的choose元素-->
<!--    当查询的条件满足第一个when的时候,就拼接第一个when里面的SQL语句-->
<!--    当查询的条件满足第二个when的时候,就拼接第二个when里面的SQL语句-->
<!--    当所有的when都不满足的时候,就拼接otherwise里面的SQL语句-->
<!--    当有多个when里面的条件都满足的时候,就拼接最靠上的一条SQL语句,并且不会执行其他when里面的语句-->
    <select id="selectStudentByIdAndName" resultType="student" >
        select * from student where 1=1
        <choose>
            <when test="name != null and name != ''">
                and name like concat('%',#{name},'%')
            </when>
            <when test="id != null and id != ''">
                and id = #{id}
            </when>
            <otherwise>
                and password is not null
            </otherwise>
        </choose>
    </select>
<!--    使用<where>来动态的处理where关键字是否添加-->
    <select id="selectByIdAndWhere" resultType="student" parameterType="student">
        select * from student
        <where>
            <if test="name != null and name !=''">
                and name like concat('%',#{name},'%')
            </if>
            <if test="id != null and id !=''">
                and id = #{id}
            </if>
        </where>
    </select>
<!--    使用set标签简化update的代码和运行效率-->
    <update id="updateBySet" parameterType="student">
        update student
            <set>
                <if test="name != null and name != ''">
                    name = #{name},
                </if>
                <if test="password != null and password != ''">
                    password = #{password},
                </if>
            </set>
        where id = #{id}
    </update>
<!--    使用<trim>标签来动态的添加where和and关键字-->
    <select id="selectByTrim" parameterType="student" resultType="student">
        select * from student
        <trim prefix="where" prefixOverrides="and">
            <if test="name != null and name !=''">
                and name like concat('%',#{name},'%')
            </if>
            <if test="id != null and id != ''">
                and id = #{id}
            </if>
        </trim>
    </select>
</mapper>

接口文件:

package Mappers;

import com.mybatis.POJO.student;

import java.util.List;

public interface dynamicSql {
    List<student> selectByIdOrName(student s);
    List<student> selectStudentByIdAndName(student s);
    List<student> selectByIdAndWhere(student s);
    int updateBySet(student s);
    List<student> selectByTrim(student s);
}

测试类:

package Mappers;

import com.mybatis.POJO.Tools.createSqlSession;
import com.mybatis.POJO.student;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class dynamicSqlTest {
    @Test
    public void selectByIdOrName(){
        SqlSession sqlSession = new createSqlSession().create();
        dynamicSql dynamicSql = new createSqlSession().createdynamicSql();
        student s = new student();
        s.setId(1);
        s.setName("张三");
        List<student> stu = sqlSession.selectList("Mappers.dynamicSql.selectByIdOrName", s);
        for(student student : stu){
            System.out.println(student.toString());
        }
    }
    @Test
    public void selectStudentByIdAndName(){
        dynamicSql dynamicSql = new createSqlSession().createdynamicSql();
        student s =new student();
//        s.setId(1);
//        s.setName("张三");
        for (student student : dynamicSql.selectStudentByIdAndName(s)) {
            System.out.println(student);
        }
    }
    @Test
    public void selectAll(){
        SqlSession sqlSession = new createSqlSession().create();
        dynamicSql dynamicSql = new createSqlSession().createdynamicSql();
        List<student> list = sqlSession.selectList("Mappers.dynamicSql.selectAll");
        for(student student : list){
            System.out.println(student.toString());
        }
    }
    @Test
    public void selectByIdAndWhere(){
        SqlSession sqlSession = new createSqlSession().create();
        dynamicSql dynamicSql = new createSqlSession().createdynamicSql();
        student s = new student();
//        s.setId(1);
//        s.setName("张三");
        for (student student : dynamicSql.selectByIdAndWhere(s)) {
            System.out.println(student.toString());
        }
    }
//    测试set标签插入数据的方法
    @Test
    public void updateBySet(){
        SqlSession sqlSession = new createSqlSession().create();
        dynamicSql dynamicSql = new createSqlSession().createdynamicSql();
        student s = new student();
        s.setId(4);
        s.setName("大海");
        s.setPassword("222333");
        int i = dynamicSql.updateBySet(s);
        if(i > 0){
            System.out.println("修改成功!");
        }
    }
//    使用<trim>标签动态的添加where关键字和and关键字
    @Test
    public void selectByTrim(){
        SqlSession sqlSession = new createSqlSession().create();
        dynamicSql dynamicSql = new createSqlSession().createdynamicSql();
        student s = new student();
        s.setId(1);
        s.setName("张三");
        for (student student : dynamicSql.selectByTrim(s)) {
            System.out.println(student.toString());
        }

    }
}

运行结果:

我们先放开两个条件,当这两个条件同时存在的时候,应该会正常的查询出一条数据:

紧接着我们就关闭id的参数,只保留name的参数作为查询条件,这时候我们能查询出两条数据:

 可以看到无论是查询单条数据还是多条数据都可以正常的查询出来 

注意点:

在我们使用<trim>标签的时候,一定要注意它的四个属性的使用,注意要添加的关键字是前缀还是后缀,以及SQL语句是否拼写错误,条件判断语句的判断条件是否正确合理。

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录页面</title> <style> .login-box { width: 300px; margin: 100px auto; padding: 20px; border: 1px solid #eee; border-radius: 8px; } input { width: 100%; padding: 8px; margin: 8px 0; box-sizing: border-box; } .btn { background: #0084ff; color: white; border: none; border-radius: 4px; cursor: pointer; } .error { color: red; text-align: center; } </style> </head> <body> <div class="login-box"> <form action="loginCheck.jsp" method="post"> 用户名: <input type="text" name="username" required placeholder="请输入用户名"><br> 密码: <input type="password" name="password" required placeholder="请输入密码"><br> <input type="submit" class="btn" value="登录"> <% String error = request.getParameter("error"); %> <% if (error != null && "1".equals(error)) { %> <div class="error">用户名或密码错误</div> <% } %> </form> </div> </body> </html><%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page import="java.sql.*" %> <%@ page import="org.mindrot.jbcrypt.BCrypt" %> <% request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) { response.sendRedirect("login.jsp?error=1"); return; } username = username.trim(); password = password.trim(); // ########## 请修改这里的数据库配置(改为你的 MySQL 信息)########## String driver = "com.mysql.cj.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/yourdb?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; String dbUser = "root"; // 你的 MySQL 用户名(默认 root) String dbPwd = "123456"; // 你的 MySQL 密码(安装时设置的) // ########################################################### Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, dbUser, dbPwd); String sql = "SELECT password FROM users WHERE username = ?"; ps = conn.prepareStatement(sql); ps.setString(1, username); rs = ps.executeQuery(); if (rs.next()) { String dbPwdHash = rs.getString("password"); if (BCrypt.checkpw(password, dbPwdHash)) { session.setAttribute("username", username); session.setMaxInactiveInterval(30 * 60); response.sendRedirect("welcome.jsp"); } else { response.sendRedirect("login.jsp?error=1"); } } else { response.sendRedirect("login.jsp?error=1"); } } catch (ClassNotFoundException e) { System.err.println("数据库驱动加载失败:" + e.getMessage()); response.sendRedirect("login.jsp?error=1"); } catch (SQLException e) { System.err.println("数据库错误:" + e.getMessage()); response.sendRedirect("login.jsp?error=1"); } catch (Exception e) { System.err.println("系统错误:" + e.getMessage()); response.sendRedirect("login.jsp?error=1"); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) {} if (ps != null) try { ps.close(); } catch (SQLException e) {} if (conn != null) try { conn.close(); } catch (SQLException e) {} } %><%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>欢迎页面</title> <style> .welcome { text-align: center; margin-top: 100px; } a { color: #0084ff; text-decoration: none; } a:hover { text-decoration: underline; } </style> </head> <body> <% String username = (String) session.getAttribute("username"); if (username == null || username.trim().isEmpty()) { response.sendRedirect("login.jsp"); return; } %> <div class="welcome"> <h1>欢迎回来,<%= username %>!</h1> <br> <a href="logout.jsp">安全注销</a> </div> </body> </html><%@ page contentType="text/html;charset=UTF-8" language="java" %> <% session.invalidate(); response.sendRedirect("login.jsp"); %>
最新发布
11-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值