SpringBoot+Mybatis-plus执行原生Sql的三种方式

一、使用Spring的JdbcTemplate

@Autowired
private JdbcTemplate jdbcTemplate;

public void queryBySql(){
    List<Map<String, Object>> lstData = jdbcTemplate.queryForList("select * from t_test");
}

二、使用Mybatis-plus的SqlRunner

        1.配置MybatisPlus:

mybatis-plus:
  global-config:
    enable-sql-runner: true

        2.执行Sql语句

public void queryBySql(){
    List<Map<String, Object>> lstData = SqlRunner.db().selectList("select * from abc");
}

三、使用Mybatis-plus的Mapper

public interface CustomMapper extends BaseMapper<Entity> {

    @Select("SELECT * FROM your_table WHERE condition = #{value}")
    List<Entity> selectByCustomSql(@Param("value") String value);

    @Select("<script>" +
            "SELECT item_id,is_assign,shop_id FROM t_order_detail_items " +
            "where shop_id = #{shopId} and is_deleted = #{status}  " +
            "</script>")
    @Results({
            @Result(property = "itemId", column = "item_id"),
            @Result(property = "isAssign", column = "is_assign"),
            @Result(property = "shopId", column = "shop_id"),
    })
    List<ShopItemVO> selectBySql(@Param("shopId") Integer shopId, @Param("status") Short status);
}

Spring Boot项目中结合MyBatis-Plus和BeetSQL,如果你想通过`InnerInterceptor`来拦截并记录MyBatisSQL执行情况,并将其保存到MySQL数据库,可以按照以下步骤操作: 1. **添加依赖**: - 首先,在`pom.xml`文件中添加MyBatis-Plus和BeetSQL的依赖: ```xml <dependencies> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> </dependency> <dependency> <groupId>com.beetlsql</groupId> <artifactId>beetlsql-spring-boot-starter</artifactId> </dependency> </dependencies> ``` 2. **配置BeetSQL**: - 在`application.properties`或`application.yml`中配置BeetSQL的数据源信息: ```properties beetlsql.datasource.url=jdbc:mysql://localhost:3306/mydatabase beetlsql.datasource.username=root beetlsql.datasource.password=your_password ``` 3. **自定义Interceptor**: - 创建一个实现了`com.baomidou.mybatisplus.core.interceptor.Interceptor`接口的类,例如`SqlLoggingInterceptor`: ```java @Slf4j public class SqlLoggingInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { // 获取原始SQL语句 Object parameter = invocation.getArgs()[0]; if (parameter instanceof SQLStatement) { SQLStatement sqlStatement = (SQLStatement) parameter; String originalSql = sqlStatement.getOriginalSql(); log.info("原始SQL: {}", originalSql); // 执行原生查询并将结果保存到BeetSQL BeetSqlExecutor executor = BeetSqlContext.get().getExecutor(); executor.setSql(originalSql); List<Record> records = executor.execute(); // 在这里处理保存到MySQL的操作,比如将records内容插入到记录表中 // 省略具体的数据库操作代码 } return invocation.proceed(); // 返回执行结果给MyBatis-Plus } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { } } ``` 4. **启用Interceptor**: - 在启动类或配置类上注册你的Interceptor: ```java @SpringBootApplication public class Application extends WebFluxConfigurerAdapter { @Autowired private SqlLoggingInterceptor interceptor; @PostConstruct public void init() { MybatisSqlSessionFactoryBean factoryBean = (MybatisSqlSessionFactoryBean) context.getBean(MybatisSqlSessionFactoryBean.class); factoryBean.getConfiguration().addInterceptors(interceptor); } //... } ``` 5. **数据持久化**: - 在上述的`intercept`方法中,你需要处理如何将查询结果(`List<Record>`)保存到MySQL,通常会涉及到数据库操作、事务管理和异常处理。 完成以上步骤后,每次MyBatis-Plus执行SQL时,都会先经过你的自定义Interceptor,拦截到的SQL会被记录并有机会发送到BeetSQL执行,同时你还可以在此过程中进行其他额外的日志记录或业务逻辑处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值