在 MyBatis 中,动态 SQL 的编写必须注意 SQL 语句的完整性和正确性。如果不慎添加不完整的条件,可能会导致生成的 SQL 语句不正确,进而引发错误。

例如,下面这个写法是有问题的:

WHERE name != null
<if test="age != null">AND age > 20</if>

这样写会导致生成的 SQL 语句在 namenull 时出现语法错误,因为 WHERE name != null 是一个无效的 SQL 语句。name != null 这样的条件不能直接放在 SQL 语句中,因为这是一个 Java 代码,而不是有效的 SQL 语句。

正确的做法是:

  1. <where> 标签内使用 <if> 标签动态地添加条件。
  2. 确保在添加条件时,SQL 语句的语法是正确的。

以下是修正后的代码:

正确的使用方式

Mapper XML 配置
<mapper namespace="com.example.UserMapper">

    <select id="selectUsers" resultType="com.example.User">
        SELECT * FROM User
        <where>
            <if test="name != null and name != ''">
                name = #{name}
            </if>
            <if test="age != null">
                AND age > 20
            </if>
        </where>
    </select>

</mapper>

解释

  1. <where> 标签<where> 标签会自动处理 ANDOR,并在需要的时候添加 WHERE 关键字。即使只有一个条件,它也能正确地生成 SQL 语句。
  2. 动态条件
    • name 为空时,name = #{name} 这部分不会生成。
    • agenull 时,AND age > 20 这部分不会生成。

示例调用

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public List<User> getUsers(String name, Integer age) {
        return userMapper.selectUsers(name, age);
    }
}

总结

  • 使用 <where> 标签:可以确保生成的 SQL 语句在没有任何条件时也是合法的。
  • 正确的 <if> 条件:在 <if> 标签内放置条件判断,并且条件判断应该是 Java 表达式,而不是 SQL 表达式。
  • 避免无效的 SQL 条件:确保所有生成的 SQL 语句都是合法的,避免无效的 SQL 片段。

通过这种方式,可以确保你的 MyBatis 查询根据不同条件动态生成 SQL 语句,避免语法错误和逻辑错误。

mypper 打印sql lomback.xml中如何做

要在 MyBatis 中打印 SQL 语句,通常会使用 MyBatis 的日志功能。MyBatis 支持多种日志框架,包括 SLF4J、Log4j 和 Logback 等。在使用 Logback 作为日志框架时,你可以通过配置 logback.xml 文件来打印 MyBatis 的 SQL 语句和参数。

以下是一个示例,展示了如何配置 Logback 以打印 MyBatis 的 SQL 语句。

1. 添加依赖

首先,确保你的项目中已经包含了 Logback 和 MyBatis 的相关依赖。如果你使用的是 Maven,可以在 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.9</version>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>

2. 配置 logback.xml

在资源目录(通常是 src/main/resources)下创建或编辑 logback.xml 文件,添加以下配置:

<configuration>
    <!-- 控制台输出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- 设置日志级别为 DEBUG -->
    <logger name="org.apache.ibatis" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>

    <logger name="java.sql.Connection" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>
    <logger name="java.sql.Statement" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>
    <logger name="java.sql.PreparedStatement" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>

    <!-- 根日志配置 -->
    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

3. 配置 MyBatis 日志实现

在 MyBatis 配置文件(mybatis-config.xml)中,指定使用 SLF4J 作为日志实现:

<?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="SLF4J"/>
    </settings>
</configuration>

4. 确保正确引入 MyBatis 和 Logback

确保在你的 Spring 配置或 Spring Boot 配置中正确引入了 MyBatis 和 Logback。如果你使用的是 Spring Boot,确保你的主类上有 @SpringBootApplication 注解,并且 application.propertiesapplication.yml 文件中配置了数据源。

示例结果

配置完成后,当你执行 MyBatis 的 SQL 操作时,你应该能在控制台看到类似以下格式的日志输出:

2024-06-18 12:34:56 [main] DEBUG org.apache.ibatis.logging.slf4j.Slf4jImpl - ooo Using Connection [jdbc:mysql://localhost:3306/mydb]
2024-06-18 12:34:56 [main] DEBUG org.apache.ibatis.logging.slf4j.Slf4jImpl - ==>  Preparing: SELECT * FROM users WHERE id = ?
2024-06-18 12:34:56 [main] DEBUG org.apache.ibatis.logging.slf4j.Slf4jImpl - ==> Parameters: 1(Long)
2024-06-18 12:34:56 [main] DEBUG org.apache.ibatis.logging.slf4j.Slf4jImpl - <==      Total: 1

通过这种方式,你可以方便地在控制台查看 MyBatis 生成的 SQL 语句和参数,以便进行调试和优化。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐