mybatis plus 怎么使用注解的方式执行原生 sql

Mybatis Plus 是 Mybatis 的增强工具,支持使用注解的方式执行原生 SQL。以下是使用注解执行原生 SQL 的示例代码:

  1. 添加注解

在需要执行原生 SQL 的方法上添加 @Select 注解,并在注解中写入 SQL 语句,例如:

@Select("SELECT * FROM user WHERE name = #{name}")User selectUserByName(String name);
  1. 使用 @Param 注解传递参数

如果 SQL 语句中需要传递参数,则需要使用 @Param 注解,例如:

@Select("SELECT * FROM user WHERE name = #{name} AND age = #{age}")User selectUserByNameAndAge(@Param("name") String name, @Param("age") Integer age);
  1. 返回结果集

如果返回结果集,则需要指定返回值类型,并且可以使用 @Results 注解来指定结果集的映射关系,例如:

@Select("SELECT * FROM user")@Results({    @Result(property = "id", column = "user_id"),    @Result(property = "name", column = "user_name"),    @Result(property = "age", column = "user_age")})List<User> selectAllUsers();

以上是使用注解执行原生 SQL 的基本示例,需要注意的是,使用注解执行原生 SQL 时,需要在 Mybatis Plus 的配置文件中开启注解支持,例如:

@Configuration@MapperScan("com.example.mapper")public class MybatisPlusConfig {
  @Bean  public ConfigurationCustomizer configurationCustomizer() {    return configuration -> configuration.setUseGeneratedShortKey(true);  }
  @Bean  public MybatisPlusInterceptor mybatisPlusInterceptor() {    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));    return interceptor;  }
  @Bean  public SqlSessionFactory sqlSessionFactory(DataSource dataSource, MybatisPlusInterceptor interceptor) throws Exception {    MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();    sqlSessionFactory.setDataSource(dataSource);    sqlSessionFactory.setPlugins(interceptor);    sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**/*.xml"));    sqlSessionFactory.setTypeAliasesPackage("com.example.model");    return sqlSessionFactory.getObject();  }}

在以上代码中,通过 @Configuration 注解将 Mybatis Plus 的配置文件注入到 Spring 容器中,在该配置文件中配置了使用注解的方式执行原生 SQL 的相关配置。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值