mybatis 或 mybatis-plus 执行 sql 的三种方式

本文介绍了mybatis和mybatis-plus中执行SQL的三种方式:配置XML文件、使用@Select注解和SqlSession直接执行。详细讨论了各种方式的适用场景,并提到了mybatis-plus中的条件构造类如QueryWrapper、UpdateWrapper等,以及如何进行条件语句的构建,如eq、like、in等。此外,文章还分享了作者的个人背景和学习资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:

mybatis 是目前非常流行的数据库框架,mybatis-plus 是 mybatis 的增强版(只做增强,不做改变),有兴趣的可以研究下。

方式一:

配置 xml 文件,该方式是比较通用的方法,适合任何 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="com.gtja.ibcenter.wechat.moudle.mapper.WeChatPushRecordMapper">

    <select id="getPushRecord"  resultType="com.gtja.ibcenter.wechat.dto.WeChatPushRecordDto">
        select job_id jobId,pusher,type,app_key appKey,app_name appName,content,cancel,pr.create_time createTime,pr.update_time updateTime
        from wechat_push_record pr join wechat_app_info ai on pr.create_app=ai.app_key
        where job_id is not null

        <if test="pusher != null and pusher != ''">
            and pusher=#{pusher}
        </if>
        <if test="type != null and type != ''">
            and type=#{type}
        </if>
        <if test="createApp != null and createApp != ''">
            and create_app=#{createApp}
        </if>
        <if test="content != null and content != ''">
            and content like concat("%",#{content},"%")
        </if>
        <if test="cancel != null and cancel != ''">
            and cancel=#{cancel}
        </if>
        <if test="startTime != null and startTime != ''">
            and pr.create_time &gt;= #{startTime}
        </if>
        <if test="endTime != null and endTime != ''">
            and pr.create_time &lt;= #{endTime}
        </if>

        order by pr.create_time desc
    </select>

</mapper>

注:大于号、小于号的写法:

原sql语句符号

转义符号

>

>

>=

>=

<

<

<=

<=

方式二:

使用 @Select 注解,该方式适合比较简单的 sql 语句,使用起来比较简单。

    @Select("select dept_code,dept_name from dept_info where source = #{source}")
    List<DeptPo> getDeptBySource(@Param("source") Integer source);

方式三:

SqlSession 执行 sql,稍微复杂,不到万不得已不建议使用。mybatis-plus 很人性化的处理了增删改查,该方法适合不想做任何配置的人。

【可参考整合 mybatis-plus 和分页查询功能到 springboot_-CSDN博客整合 mybatis-plus】。

各种 Wrapper 用于构造条件:

Wrapper

说明

Wrapper

条件构造抽象类,最顶端父类

AbstractWrapper

用于查询条件封装,生成 sql 的 where 条件

QueryWrapper

查询条件封装,不是用lambda语法

UpdateWrapper

更新条件封装,用于对象更新操作

AbstractLambdaWrapper

Lambda 语法使用 Wrapper统一处理解析

LambdaQueryWrapper

Lambda语法使用的查询Wrapper

LambdaUpdateWrapper

Lambda 更新封装Wrapper

条件语句:

查询方式

说明

setSqlSelect

设置 SELECT 查询字段

where

WHERE 语句,拼接 +WHERE 条件

and

AND 语句,拼接 +AND 字段=值

andNew

AND 语句,拼接 +AND (字段=值)

or

OR 语句,拼接 +OR 字段=值

orNew

OR 语句,拼接 +OR (字段=值)

eq

等于=

allEq

基于 map 内容等于=

ne

不等于<>

gt

大于>

ge

大于等于>=

lt

小于<

le

小于等于<=

like

模糊查询 LIKE

notLike

模糊查询 NOT LIKE

in

IN 查询

notIn

NOT IN 查询

isNull

NULL 值查询

isNotNull

IS NOT NULL

groupBy

分组 GROUP BY

having

HAVING 关键词

orderBy

排序 ORDER BY

orderAsc

ASC 排序 ORDER BY

orderDesc

DESC 排序 ORDER BY

exists

EXISTS 条件语句

notExists

NOT EXISTS 条件语句

between

BETWEEN 条件语句

notBetween

NOT BETWEEN 条件语句

addFilter

自由拼接 SQL

last

拼接在最后,例如:last(“LIMIT 1”)

示例(BaseMapper 里面有所有的方法):

int result = userMapper.insert(userPo);    // 增

QueryWrapper<UserPo> queryWrapper= new QueryWrapper<>();
queryWrapper.eq("uid", uid);
int result = userMapper.delete(queryWrapper);    // 删

UpdateWrapper<UserPo> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("uid", uid);
int result = userMapper.update(userPo, updateWrapper);    //改

QueryWrapper<UserPo> queryWrapper= new QueryWrapper<>();
queryWrapper.eq("uid", uid);
List<UserPo> list = userMapper.selectList(queryWrapper);    //查

先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦

<think>我们正在讨论MyBatis-Plus执行SQL脚本的方法。根据引用[1]、[2]、[3]、[4]、[5],我们可以总结出以下几种方式:1.**使用MyBatis的原生方式**:通过编写Mapper接口和XML文件来执行SQL(引用[1]和[3])。2.**使用@Select等注解**:在Mapper接口的方法上直接编写SQL(引用[3])。3.**使用MyBatis-PlusSql注入器**:自定义方法并注入到MyBatis-Plus中(引用[1])。4.**使用MyBatis-PlusSQL执行分析插件**:用于打印SQL语句(引用[5])。但是,用户询问的是“执行SQL脚本”,这通常指的是一次性执行多条SQL语句(例如DDL语句创建表、索引,者批量插入数据等)。在MyBatis-Plus中,我们可以通过以下方式实现:###方法一:使用MyBatis的原生方式(通过Mapper接口映射XML注解)####1.1在Mapper接口中定义方法,使用`@Update`注解(注意:这里用`@Update`是因为执行脚本可能包含多条语句,但默认情况下MyBatis不允许一条语句包含多个命令。需要配置`allowMultiQueries=true`)```javapublicinterfaceMyMapperextendsBaseMapper<YourEntity>{@Update({"<script>","CREATETABLEIFNOTEXISTStest_table(idINTPRIMARYKEY);","INSERTINTOtest_tableVALUES(1);","INSERTINTOtest_tableVALUES(2);","</script>"})voidexecuteScript();}```在数据库连接配置中需要允许执行多条语句(以MySQL为例):```propertiesspring.datasource.url=jdbc:mysql://localhost:3306/db?allowMultiQueries=true```####1.2使用XML映射文件在Mapper接口中定义方法:```javavoidexecuteScript();```在XML文件中:```xml<updateid="executeScript">CREATETABLEIFNOTEXISTStest_table(idINTPRIMARYKEY);INSERTINTOtest_tableVALUES(1);INSERTINTOtest_tableVALUES(2);</update>```###方法二:使用JdbcTemplate(非MyBatis-Plus特有,但Spring集成)如果不想在Mapper中写,可以直接使用Spring的JdbcTemplate:```javaimportorg.springframework.jdbc.core.JdbcTemplate;importorg.springframework.stereotype.Service;@ServicepublicclassSqlScriptService{privatefinalJdbcTemplatejdbcTemplate;publicSqlScriptService(JdbcTemplatejdbcTemplate){this.jdbcTemplate=jdbcTemplate;}publicvoidexecuteScript(Stringsql){jdbcTemplate.execute(sql);}}```调用时传入完整的SQL脚本字符串(多条语句用分号隔开),同样需要配置`allowMultiQueries=true`。###方法三:使用MyBatis-PlusSqlRunner(适用于执行任意SQL)```javaimportcom.baomidou.mybatisplus.extension.toolkit.SqlRunner;//执行SQL脚本(多条语句)publicvoidexecuteScript(){Stringsql="CREATETABLEIFNOTEXISTStest_table(idINTPRIMARYKEY);"+"INSERTINTOtest_tableVALUES(1);"+"INSERTINTOtest_tableVALUES(2);";SqlRunner.db().execute(sql);}```注意:`SqlRunner`需要配置数据库连接,并且同样需要允许执行多条语句。###注意事项1.**多条语句执行**:默认情况下,为了安全,JDBC不允许一条语句中包含多个命令。必须通过连接参数开启(如MySQL的`allowMultiQueries=true`)。2.**事务管理**:执行多条语句时,如果需要事务支持,确保在方法上添加`@Transactional`注解。3.**SQL注入风险**:避免将用户输入的字符串直接拼接到SQL脚本中执行,以防SQL注入攻击。4.**性能**:执行大量SQL脚本时,考虑使用批处理。###总结|方法|适用场景|注意事项||--------------|----------------------------------------|------------------------------||Mapper注解/XML|需要与MyBatisMapper集成|需配置allowMultiQueries||JdbcTemplate|简单直接,不依赖MyBatis|需配置allowMultiQueries||SqlRunner|MyBatis-Plus提供的快捷工具|需配置allowMultiQueries|>提示:生产环境中执行DDL(如创建表、索引)建议使用数据库迁移工具(如FlywayLiquibase)[^1][^2]。[^1]:MyBatis-plus执行自定义SQL[^2]:解决SQL语句错误[^3]:mybatismybatis-plus执行sql三种方式[^4]:MyBatis-Plus(实用方法)[^5]:MyBatis-Plus执行SQL分析打印§§相关问题§§1.在MyBatis-Plus中如何安全地防止SQL注入?2.如何配置MyBatis-Plus以允许执行多条SQL语句?3.MyBatis-PlusSqlRunner类还有哪些常用方法?4.使用JdbcTemplate和MyBatis-Plus执行SQL脚本的主要区别是什么?5.在SpringBoot中如何管理执行SQL脚本的事务?</think>在 MyBatis-Plus执行 SQL 脚本主要有以下四种方法,适用于不同场景: ### 方法 1:使用 `@Select` 等注解(简单 SQL) ```java public interface UserMapper extends BaseMapper<User> { @Select("CREATE INDEX idx_name_age ON user(name, age);" + "ALTER TABLE user ADD COLUMN email VARCHAR(100);") void executeSqlScript(); } ``` **特点**: - 适用于简单、静态的 SQL 脚本 - 直接在方法上声明 SQL 语句 - 支持多语句执行(需配置 `allowMultiQueries=true`) ### 方法 2:XML 映射文件(推荐复杂 SQL) **Mapper 接口**: ```java void executeCustomScript(); ``` **XML 文件 (`UserMapper.xml`)**: ```xml <update id="executeCustomScript"> <!-- 支持多语句执行 --> DROP TABLE IF EXISTS temp_table; CREATE TABLE temp_table(id INT PRIMARY KEY); INSERT INTO temp_table VALUES (1),(2); </update> ``` **配置**(启用多语句): ```properties # application.properties spring.datasource.url=jdbc:mysql://localhost:3306/db?allowMultiQueries=true ``` ### 方法 3:SqlRunner 工具类(动态 SQL) ```java SqlRunner runner = new SqlRunner(getConnection()); String sql = "CREATE INDEX idx_status ON orders(status);" + "UPDATE orders SET discount=0.9 WHERE amount>1000;"; // 执行脚本 runner.run(sql); // 查询示例(引用[5]) List<Map<String, Object>> result = runner.selectList("SELECT * FROM orders"); ``` ### 方法 4:自定义 SQL 注入器(复用复杂操作) ```java // 1. 定义自定义方法 public class BatchInsert extends AbstractMethod { public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) { String sql = "<script>INSERT INTO %s %s VALUES %s</script>"; // 构建动态SQL... return addInsertMappedStatement(...); } } // 2. 注册注入器 public class MySqlInjector extends DefaultSqlInjector { public List<AbstractMethod> getMethodList(Class<?> mapperClass) { List<AbstractMethod> methods = super.getMethodList(mapperClass); methods.add(new BatchInsert()); // 添加自定义方法 return methods; } } // 3. 调用 userMapper.batchInsert(list); // 执行预定义的SQL操作 ``` ### 关键配置注意事项 1. **多语句执行**: ```properties # MySQL spring.datasource.url=jdbc:mysql:///db?allowMultiQueries=true # PostgreSQL spring.datasource.url=jdbc:postgresql:///db?prepareThreshold=0 ``` 2. **SQL 分析打印(调试用)**: ```java @Bean @Profile("dev") // 只在开发环境启用 public PerformanceInterceptor performanceInterceptor() { PerformanceInterceptor interceptor = new PerformanceInterceptor(); interceptor.setFormat(true); // 格式化SQL输出 return interceptor; } ``` 3. **事务控制**: ```java @Transactional public void executeScripts() { userMapper.executeCustomScript(); orderMapper.updateDiscounts(); } ``` ### 方法对比 | 场景 | 推荐方法 | 优势 | |--------------------------|----------------|------------------------------| | 简单静态 SQL | `@Select` 注解 | 快速直接 | | 复杂/多语句 SQL | XML 映射 | 易维护,支持动态 SQL | | 运行时动态生成 SQL | SqlRunner | 无需 Mapper 接口 | | 需复用的复杂操作 | SQL 注入器 | 封装为通用方法,调用简洁 | > **生产建议**:复杂脚本推荐使用 XML 映射 + Flyway 数据库迁移工具组合管理[^1][^2]。执行 DDL 操作前务必备份数据,并在测试环境验证 SQL 语法正确性[^2]。 [^1]: MyBatis-plus执行自定义SQL [^2]: 解决SQL语句错误 [^3]: mybatis mybatis-plus 执行 sql三种方式 [^4]: MyBatis-Plus(实用方法) [^5]: MyBatis-Plus 执行SQL分析打印
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值