Spring Data Jpa之nativeQuery(仅案例

2023-05-16

Spring Data Jpa 默认实现是hibernate,我们都知道hibernate使用HQL查询(Hibernate是JPA的实现之一),而不推荐使用sql查询,因为这样子就跟具体数据库耦合了,违背了初衷,但是没有union语句,我也只能用原生了。。。

接口声明:

	@Query(nativeQuery = true ,value = "SELECT topicId ,`type`  from " +
            "(SELECT topic_id as topicId , 2 as type ,create_time FROM collection where user_id in (SELECT focus_id from relation where fan_id = 1) " +
            "UNION " +
            "SELECT id as topicId , 1 as type , create_time FROM topic WHERE user_id in (SELECT focus_id from relation where fan_id = 1 )) " +
            "temp ORDER BY temp.create_time DESC;")
    List<Object> getAll();

    @Query(nativeQuery = true ,value = "SELECT topicId ,`type`  from " +
            "(SELECT topic_id as topicId , 2 as type ,create_time FROM collection where user_id in (SELECT focus_id from relation where fan_id = 1) " +
            "UNION " +
            "SELECT id as topicId , 1 as type , create_time FROM topic WHERE user_id in (SELECT focus_id from relation where fan_id = 1 )) " +
            "temp ORDER BY temp.create_time DESC;")
    List<Object[]> getAll2();

    @Query(nativeQuery = true ,value = "SELECT topicId ,`type`  from " +
            "(SELECT topic_id as topicId , 2 as type ,create_time FROM collection where user_id in (SELECT focus_id from relation where fan_id = 1) " +
            "UNION " +
            "SELECT id as topicId , 1 as type , create_time FROM topic WHERE user_id in (SELECT focus_id from relation where fan_id = 1 )) " +
            "temp ORDER BY temp.create_time DESC;")
    List<BigInteger[]> getAll3();

    @Query(nativeQuery= true ,value = "SELECT topicId ,`type`  from " +
            "(SELECT topic_id as topicId , 2 as type ,create_time FROM collection where user_id in (SELECT focus_id from relation where fan_id = ?1) " +
            "UNION " +
            "SELECT id as topicId , 1 as type , create_time FROM topic WHERE user_id in (SELECT focus_id from relation where fan_id = ?1 )) " +
            "temp ORDER BY temp.create_time DESC limit ?2 , ?3")
    List<Object[]> getAllRelationTopic(Long fanId  , Integer startLoacl , Integer size);

这里注意getAll、getAll2、getAll3的返回值,这三个方法是例子,getAllRelationTopic是正常我最终要写的逻辑
四个sql注解,使用nativeQuery,就是原始sql查询,返回一个集合的Object[](对象数组),
接收时可以是Object、Object[],其他类型不能接受

Spring Boot测试:(Spring boot测试类添加 @RunWith(SpringRunner.class) 和 @SpringBootTest 注解)

	@Test
    public void getAll() {

        List<Object> collection = repository.getAll();
        for (int i = 0; i < collection.size(); i++) {
            Object[] col = (Object[]) collection.get(i);
            RelationTopic relationTopic = new RelationTopic(((BigInteger) col[0]).longValue(), ((BigInteger) col[1]).intValue());
            System.out.println(relationTopic.toString());
        }
        System.out.println();
    }

    @Test
    public void getAll2() {

        List<Object[]> collection = repository.getAll2();
        for (int i = 0; i < collection.size(); i++) {
            Object[] col = collection.get(i);
            RelationTopic relationTopic = new RelationTopic(((BigInteger) col[0]).longValue(), ((BigInteger) col[1]).intValue());
            System.out.println(relationTopic.toString());
        }
        System.out.println();
    }

    @Test
    public void getAll3() {
        //java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.math.BigInteger;
        List<BigInteger[]> collection = repository.getAll3();
        for (int i = 0; i < collection.size(); i++) {
            BigInteger[] col = collection.get(i);
            RelationTopic relationTopic = new RelationTopic(col[0].longValue(), col[1].intValue());
            System.out.println(relationTopic.toString());
        }
        System.out.println();
    }

    @Test
    public void getAllRelationTopic() {
        List<Object[]> collection = repository.getAllRelationTopic(1L , 0 , 5);
        List<Long> longCollection = new ArrayList<>();
        for (int i = 0; i < collection.size(); i++) {
            Object[] col = collection.get(i);
            RelationTopic relationTopic = new RelationTopic(((BigInteger) col[0]).longValue(), ((BigInteger) col[1]).intValue());
            longCollection.add(relationTopic.getTopicId());
            System.out.println(relationTopic.toString());
        }
        System.out.println();
    }

测试方法getAll、getAll2、getAll3是对上面sql的测试,getAll3会报错,因为转不了类型
下面是getAllRelationTopic测试方法的解释
这里我将返回的数组构建成一个类。数字类型都是BigInteger,所以将Object数组元素转成BigInteger,其中接受值为List< BigInteger[]>的方法报错,可以知道只能用Object或者Object数组才能接受返回值,具体Object怎么组成的,通过Debug来查看具体类型,再转成你要的类型。


顺便记录一下,JPQL怎么生成新类:

@Query("select new space.xxhui.ec.interaction.POJO.RelationTopic( c.topicId , 2 ,c.createTime) from CollectionEntity c where c.userId in (select r.focusId from RelationEntity r where r.fanId = ?1 ) ")
    List<RelationTopic> getRelationTopic(Long fanId);

就是:new 包路径+类构造方法 ,这个也能看出,我这个类有个接受三个值的构造方法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Data Jpa之nativeQuery(仅案例 的相关文章

随机推荐

  • Ubuntu 安装git及git命令

    1 检查git是否已经安装 xff0c 输入git version命令即可 xff0c 如果没有显示版本号表示没有安装git 2 安装git sudo apt get install git 3 配置git全局环境 git config g
  • Bad method handle type 7异常解决

    在利用androidx版本写demo时 xff0c 在添加了一些依赖后 xff0c 遇到了java lang ClassNotFoundExceptionbug xff0c 这就很奇怪了 xff0c 我就添加rxjava3的依赖 xff0c
  • linux防火墙添加端口

    iptables版 iptables nL line number vi etc sysconfig iptables 添加以下语句 A RH Firewall 1 INPUT p tcp m state state NEW m tcp d
  • 如何在webstorm使用eslint检查代码规范

    一 安装esLint xff08 一 xff09 打开项目代码 xff0c 进入terminal xff08 二 xff09 安装esLint 1 安装esLint npm install eslint span class token o
  • VUE基本格式

    96 VUE基本格式 lt template gt lt div gt lt div gt lt template gt lt script gt export default beforeCreate function data retu
  • Decode Ways 解码方法

    一条包含字母 A Z 的消息通过以下方式进行了编码 xff1a 39 A 39 gt 1 39 B 39 gt 2 39 Z 39 gt 26 给定一个只包含数字的非空 字符串 xff0c 请计算解码方法的总数 示例 1 输入 34 12
  • CAS单点登录6 - 服务端自定义返回的用户信息

    原理 返回的用户信息是在deployerConfigContext xml中的配置的 既然想自定义返回的用户信息 xff0c 那么继承org jasig services persondir support StubPersonAttrib
  • kotlin-android-extensions处理方案

    不幸的是 xff0c kotlin android extensions官方提示过时了 xff0c 而且列出来了几个过时的原因 但是这些我都不在乎 xff0c 也不觉得会对我产生什么影响 那可以尝试这样吧 xff0c 再被as彻底删除之后
  • Fragment跳转到Activity无动画

    这段代码无效果 xff1a startActivity span class hljs keyword new span Intent mContext GalleryActivity span class hljs keyword cla
  • Matlab科研绘图颜色补充(特别篇)—51种中国传统颜色

    前几天在找资料的时候 xff0c 发现了这个 xff1a 这是由 中国国家地理 杂志社制作的色卡 xff0c 据说总共包含98种中国传统颜色 xff0c 但目前能找到的就是这51种 xff08 而且比较模糊 xff09 百草霜 竹月 胭脂
  • Tensorflow Lite GPU在安卓上实现

    在近期工作中 xff0c 采用TensorFlow Lite将ssd mobilenet目标检测模型移植安卓机上 从安卓机测试的效果来看 xff0c 非量化的模型每帧图像推理的速率较慢 为压缩模型提升推理速度 xff0c 采用了减少模型深度
  • 面试官让我手写一个生产者消费者模式

    不知道你是否遇到过面试官让你手写生产者消费者代码 别说 xff0c 前段时间有小伙伴还真的遇到了这种情况 当时是一脸懵逼 但是 xff0c 俗话说 xff0c 从哪里跌倒就要从哪里爬起来 既然这次被问到了 xff0c 那就回去好好研究一下
  • 2-11 附:文档的基本操作 - 查询

  • ActiveMQ的简单Topic实现案例

    首先我们在这里要说一下消息中间件中有两个角色 xff0c 生产者Producer与消费者Consumer xff0c 简单理解即使发发送消息者与接收消息者 xff0c 在编写代码之前我们需要将下载到的ActiveMQ压缩包中的activem
  • Java学习之旅--集合的使用(Map集合)

    好几天没有更新了 xff0c 主要是最近正在学习集合 xff0c 让博主有点头大 所以就耽误了 xff1a 现在就来说说集合里的Map集合 xff1a import java span class hljs preprocessor uti
  • CartPole 强化学习详解1 - DQN

    工作中常会接触到强化学习的内容 xff0c 自己以gym环境中的Cartpole为例动手实现一下 xff0c 记录点实现细节 环境 xff1a python 61 3 6 13 xff1b pytorch 61 1 10 2 目录 1 gy
  • Java学习之旅--线程的创建方法

    线程创建的方法一 span class hljs keyword package span com geminno day14 createthread1 span class hljs keyword public span span c
  • select搜索功能实现

    select搜索功能实现 最近在找工作 没时间写博客 现在找到了 就发发工作上的代码吧 xff01 今天我们说说select标签的搜索功能 xff1b 拿到任务时 xff0c 我先想到就是上网找资料 xff0c 最后看到的都是各种jquer
  • Spring源码--IOC容器实现(5)--Bean对象的创建

    前言 Github xff1a https github com yihonglei thinking in spring 在前面文章中分析了容器初始化过程 xff0c 已经建立了一个可以使用的容器 1 xff09 BeanDefiniti
  • Spring Data Jpa之nativeQuery(仅案例

    Spring Data Jpa 默认实现是hibernate xff0c 我们都知道hibernate使用HQL查询 xff08 Hibernate是JPA的实现之一 xff09 xff0c 而不推荐使用sql查询 xff0c 因为这样子就