mybatis plus 怎么使用注解的方式执行原生 sql |
您所在的位置:网站首页 › mybatis plus 源码 › mybatis plus 怎么使用注解的方式执行原生 sql |
0
分享至
用微信扫码二维码 分享至好友和朋友圈 Mybatis Plus 是 Mybatis 的增强工具,支持使用注解的方式执行原生 SQL。以下是使用注解执行原生 SQL 的示例代码: 添加注解 在需要执行原生 SQL 的方法上添加 @Select 注解,并在注解中写入 SQL 语句,例如: @Select("SELECT * FROM user WHERE name = #{name}")User selectUserByName(String name); 使用 @Param 注解传递参数 如果 SQL 语句中需要传递参数,则需要使用 @Param 注解,例如: @Select("SELECT * FROM user WHERE name = #{name} AND age = #{age}")User selectUserByNameAndAge(@Param("name") String name, @Param("age") Integer age); 返回结果集 如果返回结果集,则需要指定返回值类型,并且可以使用 @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 selectAllUsers(); 以上是使用注解执行原生 SQL 的基本示例,需要注意的是,使用注解执行原生 SQL 时,需要在 Mybatis Plus 的配置文件中开启注解支持,例如: @Configuration@MapperScan("com.example.mapper")public class MybatisPlusConfig {@Beanpublic ConfigurationCustomizer configurationCustomizer() {return configuration -> configuration.setUseGeneratedShortKey(true);}@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}@Beanpublic 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 原文链接;https://xie.infoq.cn/article/99fa1492c6226df778134274d 特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。 Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services. /阅读下一篇/ 返回网易首页 下载网易新闻客户端 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |