MyBatis快速入门——第四章、mybatis动态sql_if_choose_when

简介: MyBatis快速入门——第四章、mybatis动态sql_if_choose_when

测试sql

数据库名称【mytest】,编码类型【utf8】


DROP TABLE IF EXISTS `product`;
CREATE TABLE `product`  (
  `id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `createDate` datetime(0) NOT NULL,
  `modifyDate` datetime(0) NOT NULL,
  `productName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `productTitle` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `productPrice` decimal(10, 2) NOT NULL,
  `productCount` int(8) NOT NULL,
  `productType` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `productColor` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `productWeight` double NULL DEFAULT NULL,
  `productStatus` int(1) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
INSERT INTO `product` VALUES ('b383581fd20211ec84b500e070bfdb54', '2022-05-12 22:49:18', '2022-05-12 22:49:18', '外星人M15', '高端外星人', 13499.00, 299, '外星人', 'black', 3300, 1);
INSERT INTO `product` VALUES ('b3839547d20211ec84b500e070bfdb54', '2022-05-12 22:49:18', '2022-05-12 22:49:18', 'ThinkBook', '联想', 4599.00, 159, '联想', 'gray', 2250, 1);
INSERT INTO `product` VALUES ('b383d49dd20211ec84b500e070bfdb54', '2022-05-12 22:49:18', '2022-05-12 22:49:18', '戴尔G15', '戴尔', 7499.00, 179, '戴尔', 'gray', 2270, 1);
INSERT INTO `product` VALUES ('b384180cd20211ec84b500e070bfdb54', '2022-05-12 22:49:18', '2022-05-12 22:49:18', 'RedmiBook Pro15', '小米', 4499.00, 699, '小米', 'black', 2500, 1);
INSERT INTO `product` VALUES ('b38457bed20211ec84b500e070bfdb54', '2022-05-12 22:49:18', '2022-05-12 22:49:18', '华硕a豆', '华硕', 3699.00, 799, '华硕', 'pink', 2100, 1);
INSERT INTO `product` VALUES ('f6715eb2d20111ec84b500e070bfdb54', '2022-05-12 22:44:01', '2022-05-12 22:44:01', '拯救者Y7700P', '2022新品拯救者', 7399.00, 199, '联想', 'gray', 2200, 1);

mybatis-config.xml文件

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <typeAliases>
        <package name="com.item.model"/>
    </typeAliases>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mytest?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="12345678"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/item.mapper/ProductMapper.xml"></mapper>
    </mappers>
</configuration>

ProductMapper.xml文件

情况1、纯if判断

<?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="com.item.mapper.ProductMapper">
    <select id="GetInfo" resultType="Product">
        select * from product
        <if test="productName!=null or productType!=null or productColor!=null ">
            where 1=1
        </if>
                <!-- 模糊查询 -->
                <if test="productName!=null">
                   and productName like "%${productName}%"
                </if>
                <!-- 类型筛选 -->
                <if test="productType!=null">
                    and productType="${productType}"
                </if>
                <!-- 颜色筛选 -->
                <if test="productColor!=null">
                    and productColor="${productColor}"
                </if>
    </select>
</mapper>

情况2:choose when(if else)

<?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="com.item.mapper.ProductMapper">
    <select id="GetInfo" resultType="Product">
        select * from product
        <if test="productName!=null or productType!=null or productColor!=null ">
            where 1=1
        </if>
        <choose>
            <when test="productName!=null">
                and productName like "%${productName}%"
            </when>
            <when test="productType!=null">
                and productType = "${productType}"
            </when>
            <when test="productType!=null">
                and productColor = "${productColor}"
            </when>
        </choose>
    </select>
</mapper>


数据库工具类

package com.item.common;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
public class JDBC {
    public static SqlSessionFactory GetConn(){
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
            return factory;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Product

package com.item.model;
import java.math.BigDecimal;
import java.util.Date;
public class Product {
    private String id;
    private Date createDate;
    private Date modifyDate;
    private String productName;
    private String productTitle;
    private BigDecimal productPrice;
    private int productCount;
    private String productType;
    private String productColor;
    private double productWeight;
    private int productStatus;
    @Override
    public String toString() {
        return "Product{" +
                "id='" + id + '\'' +
                ", createDate=" + createDate +
                ", modifyDate=" + modifyDate +
                ", productName='" + productName + '\'' +
                ", productTitle='" + productTitle + '\'' +
                ", productPrice=" + productPrice +
                ", productCount=" + productCount +
                ", productType='" + productType + '\'' +
                ", productColor='" + productColor + '\'' +
                ", productWeight=" + productWeight +
                ", productStatus=" + productStatus +
                '}';
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public String getProductTitle() {
        return productTitle;
    }
    public void setProductTitle(String productTitle) {
        this.productTitle = productTitle;
    }
    public BigDecimal getProductPrice() {
        return productPrice;
    }
    public void setProductPrice(BigDecimal productPrice) {
        this.productPrice = productPrice;
    }
    public int getProductCount() {
        return productCount;
    }
    public void setProductCount(int productCount) {
        this.productCount = productCount;
    }
    public String getProductType() {
        return productType;
    }
    public void setProductType(String productType) {
        this.productType = productType;
    }
    public String getProductColor() {
        return productColor;
    }
    public void setProductColor(String productColor) {
        this.productColor = productColor;
    }
    public double getProductWeight() {
        return productWeight;
    }
    public void setProductWeight(double productWeight) {
        this.productWeight = productWeight;
    }
    public int getProductStatus() {
        return productStatus;
    }
    public void setProductStatus(int productStatus) {
        this.productStatus = productStatus;
    }
}


ProductMapper

package com.item.mapper;
import com.item.model.Product;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ProductMapper {
    List<Product> GetInfo(@Param("productName") String productName,
                          @Param("productType") String productType,
                          @Param("productColor") String productColor);
}
ProduceDAO
package com.item.dao;
import com.item.common.JDBC;
import com.item.mapper.ProductMapper;
import com.item.model.Product;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
public class ProduceDAO {
    /**
     * 各类查询
     * @param productName (商品名称)
     * @param productType (商品类型)
     * @param productColor (商品颜色)
     * @return
     */
    public static List<Product> GetInfo(String productName,
                          String productType,
                          String productColor) {
        SqlSessionFactory factory = JDBC.GetConn();
        SqlSession session = factory.openSession();
        ProductMapper db = session.getMapper(ProductMapper.class);
        List<Product> list = db.GetInfo(productName, productType, productColor);
        session.close();
        return list;
    }
}


Action

package com.item.action;
import com.item.dao.ProduceDAO;
import com.item.model.Product;
import java.util.List;
public class Action {
    public static void main(String[] args){
        List<Product> list = ProduceDAO.GetInfo(null,"联想",null);
        for (Product p : list) {
            System.out.println("编号"+p.getId());
            System.out.println("创建时间"+p.getCreateDate());
            System.out.println("修改时间"+p.getModifyDate());
            System.out.println("产品名称"+p.getProductName());
            System.out.println("产品标题"+p.getProductTitle());
            System.out.println("产品价格"+p.getProductPrice());
            System.out.println("产品数量"+p.getProductCount());
            System.out.println("品牌类型"+p.getProductType());
            System.out.println("重量"+p.getProductWeight());
            System.out.println("状态"+(p.getProductStatus()==1?"上架":"下架"));
        }
    }
}


执行效果:


image.png


注意1=1用于肯定查询,不是所有的1=1都是注入攻击。  


相关文章
|
6月前
|
SQL XML Java
通过MyBatis的XML配置实现灵活的动态SQL查询
总结而言,通过MyBatis的XML配置实现灵活的动态SQL查询,可以让开发者以声明式的方式构建SQL语句,既保证了SQL操作的灵活性,又简化了代码的复杂度。这种方式可以显著提高数据库操作的效率和代码的可维护性。
403 18
|
11月前
|
SQL Java 数据库连接
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
|
10月前
|
SQL Java 数据库连接
MyBatis动态SQL字符串空值判断,这个细节99%的程序员都踩过坑!
本文深入探讨了MyBatis动态SQL中字符串参数判空的常见问题。通过具体案例分析,对比了`name != null and name != &#39;&#39;`与`name != null and name != &#39; &#39;`两种写法的差异,指出后者可能引发逻辑混乱。为避免此类问题,建议在后端对参数进行预处理(如trim去空格),简化MyBatis判断逻辑,提升代码健壮性与可维护性。细节决定成败,严谨处理参数判空是写出高质量代码的关键。
1361 0
|
6月前
|
SQL Java 数据库连接
SSM相关问题-1--#{}和${}有什么区别吗?--Mybatis都有哪些动态sql?能简述一下动 态sql的执行原理吗?--Spring支持的几种bean的作用域 Scope
在MyBatis中,`#{}`是预处理占位符,可防止SQL注入,适用于大多数参数传递场景;而`${}`是直接字符串替换,不安全,仅用于动态表名、列名等特殊场景。二者在安全性、性能及使用场景上有显著区别。
126 0
|
9月前
|
SQL XML Java
菜鸟之路Day35一一Mybatis之XML映射与动态SQL
本文介绍了MyBatis框架中XML映射与动态SQL的使用方法,作者通过实例详细解析了XML映射文件的配置规范,包括namespace、id和resultType的设置。文章还对比了注解与XML映射的优缺点,强调复杂SQL更适合XML方式。在动态SQL部分,重点讲解了`&lt;if&gt;`、`&lt;where&gt;`、`&lt;set&gt;`、`&lt;foreach&gt;`等标签的应用场景,如条件查询、动态更新和批量删除,并通过代码示例展示了其灵活性与实用性。最后,通过`&lt;sql&gt;`和`&lt;include&gt;`实现代码复用,优化维护效率。
921 5
|
11月前
|
SQL Java 数据库连接
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
|
11月前
|
SQL 缓存 Java
框架源码私享笔记(02)Mybatis核心框架原理 | 一条SQL透析核心组件功能特性
本文详细解构了MyBatis的工作机制,包括解析配置、创建连接、执行SQL、结果封装和关闭连接等步骤。文章还介绍了MyBatis的五大核心功能特性:支持动态SQL、缓存机制(一级和二级缓存)、插件扩展、延迟加载和SQL注解,帮助读者深入了解其高效灵活的设计理念。
|
11月前
|
SQL XML Java
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
329 0
|
8月前
|
Java 数据库连接 数据库
Spring boot 使用mybatis generator 自动生成代码插件
本文介绍了在Spring Boot项目中使用MyBatis Generator插件自动生成代码的详细步骤。首先创建一个新的Spring Boot项目,接着引入MyBatis Generator插件并配置`pom.xml`文件。然后删除默认的`application.properties`文件,创建`application.yml`进行相关配置,如设置Mapper路径和实体类包名。重点在于配置`generatorConfig.xml`文件,包括数据库驱动、连接信息、生成模型、映射文件及DAO的包名和位置。最后通过IDE配置运行插件生成代码,并在主类添加`@MapperScan`注解完成整合
1375 1
Spring boot 使用mybatis generator 自动生成代码插件
|
11月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
856 0