Spring Data Jpa之nativeQuery(仅案例

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 包路径+类构造方法 ,这个也能看出,我这个类有个接受三个值的构造方法。

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Data JPA中的@Query注解可以在抽象方法上使用。该注解允许我们直接编写自定义的SQL查询语句,以替代默认的基于方法命名规则的查询。 使用@Query注解,我们可以在抽象方法上定义自己的查询语句。可以通过在注解中编写原生的SQL查询语句或者使用JPQL查询语句来完成。 当使用原生的SQL查询语句时,我们需要设置nativeQuery参数为true。这样Spring Data JPA就会将查询结果与实体类进行映射。 如果使用JPQL查询语句,我们可以通过在查询语句中引用实体类和其属性来构建查询语句。Spring Data JPA会根据查询语句的返回类型自动进行结果映射。 在@Query注解中,我们还可以使用命名参数或者索引参数来指定查询参数。通过在查询方法的参数前添加@Param注解,我们可以将方法参数与查询参数进行映射。 除了定义查询语句,@Query注解还可以指定查询的排序方式、分页和锁定等。我们可以使用关键字ORDER BY来设置排序字段,使用关键字LIMIT和OFFSET来设置分页查询的起始位置和返回记录数。同时,我们还可以使用关键字FOR UPDATE来设置查询结果的锁定。 通过在抽象方法上使用@Query注解,我们可以实现更加灵活和复杂的查询需求。它为我们提供了一种强大的方式来利用Spring Data JPA进行自定义查询,以满足特定业务场景的需求。 ### 回答2: Spring Data JPA提供了一个 @Query 注解,可以在抽象方法上使用。 @Query 注解用于在 Repository 接口中定义查询方法的具体查询语句。通过使用 @Query 注解,我们可以将自定义的 JPQL 或者 SQL 语句与方法绑定在一起。 使用 @Query 注解有以下几个优点: 1. 灵活性:可以使用自定义的查询语句,满足特定的数据查询需求。 2. 类型安全:由于使用了命名参数或者索引参数,可以避免 SQL 注入等安全问题。 3. 提高代码可读性:通过在方法上添加 @Query 注解,可以直接看到方法的具体查询是如何实现的,提高代码的可读性和可维护性。 4. 内置分页支持:可以在 @Query 注解中使用内置的分页查询方法,如 Pageable 和 Sort。 使用 @Query 注解时,可以将查询语句写在注解的 value 属性中。语句可以是原生的 SQL 语句,也可以是 JPQL 查询语句。在查询语句中,可以使用实体类的属性名来代替数据库表字段名。 另外,@Query 注解还支持使用命名参数和索引参数。命名参数使用冒号(:)加参数名的方式,在方法参数中使用 @Param 注解指定参数名。索引参数使用问号(?)加索引位置的方式。 需要注意的是,使用 @Query 注解时,方法的返回类型可以是具体的实体类,也可以是包装类、List、Set 或者其他集合类。如果需要分页查询,返回类型可以是 Page 或者 Slice 类型。 总的来说,通过在抽象方法中使用 Spring Data JPA 的 @Query 注解,可以更加灵活地定义自定义查询,提高代码的可读性和可维护性。 ### 回答3: Spring Data JPA提供了 @Query 注解,它可以用在抽象方法上,用于自定义查询语句。 使用 @Query 注解,我们可以在抽象方法上定义自己的JPQL(Java Persistence Query Language)或SQL查询语句。通过在注解中定义查询语句,我们可以灵活地执行各种复杂的查询操作。 在定义查询语句时,我们可以使用实体类的属性名来引用实体的字段,并且可以使用 JPA 提供的各种查询关键字和函数进行组合。除此之外,我们还可以使用一些特殊的 JPA 提供的关键字,如:distinct、is not null、is null、order by等。 在定义查询语句时,@Query 注解还支持使用命名参数和位置参数两种方式来传递参数。命名参数使用 :paramName 的方式来引用参数,而位置参数使用 ?1、?2 等符号来引用参数。我们可以根据实际情况选择适合的参数传递方式。 除了定义查询语句,@Query 注解还有其他一些属性。例如,我们可以使用 @Modifying 注解来告诉 Spring Data JPA 这个查询是一个更新操作,需要通过 @Transactional 注解来开启事务。另外,还可以使用 @Query 注解的 nativeQuery 属性来指示是否执行原生 SQL 查询。 总之,通过在抽象方法上使用 @Query 注解,我们可以自定义我们需要的查询语句,使得我们可以方便地执行各种复杂的查询操作。这样,在使用 Spring Data JPA 进行数据访问时,我们就能够更加灵活地控制查询操作,并且减少重复代码的编写。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值