是否可以在 Spring Repository @Query 注释中使用 Array 对象作为参数?

Posted

技术标签:

【中文标题】是否可以在 Spring Repository @Query 注释中使用 Array 对象作为参数?【英文标题】:Is it possible to use an Array object as a parameter in Spring Repository @Query annotation? 【发布时间】:2014-05-21 01:05:26 【问题描述】:

Spring Repository @Query annotation 中是否可以使用 Array 对象作为参数?

我正在尝试检索列节点存在于字符串数组中的表中的所有行。是否可以使用 Spring 存储库中的 @Query 注释一次完成?

这是我的位置实体:

@Entity
@Table(name = "LOCATIONS")
public class Location extends Measurement

    private String latitude;
    private String nsIndicator;

    private String longitude;
    private String ewIndicator;

    @ManyToOne
    @JoinColumn(name="node")
    private Node node;

node 引用 Node 类的地方,它在数据库中映射为 BIGINT。

我有一个这样的存储库:

public interface LocationRepository extends CrudRepository<Location, Long>

    @Query(value=
            "SELECT l1.node, l1.id, l1.latitude, l1.longitude " +
            "FROM LOCATIONS l1 WHERE l1.node IN (:ids)", 
            nativeQuery=true)
    List<Location> findMeasureByIds(@Param("ids") String[] ids);

在那里您可以看到我正在尝试执行的查询,但它不起作用。我不知道是否可以在那里使用数组,或者参数必须只是字符串和/或整数,我在任何地方都找不到。

我尝试了几种组合,例如使用格式正确的简单字符串或长数组。但到目前为止没有任何效果。

提前致谢。

解决方案:

@Query(value="SELECT * FROM LOCATIONS l1 " + 
             "INNER JOIN (SELECT node, MAX(id) AS id FROM LOCATIONS GROUP BY node) l2 " + 
             "ON l1.node = l2.node AND l1.id = l2.id " + 
             "WHERE l1.node IN :ids", nativeQuery=true) 
List<Location> findLastLocationByIds(@Param("ids") Set<Long> ids);

我为查询添加了更多功能,因为我需要检索为每个节点标识符插入的最后一行。所以有 MAX 函数和 INNER JOIN 来完成这项工作。

【问题讨论】:

【参考方案1】:

使用集合而不是数组 (Set&lt;String&gt;),并确保它不为空(否则查询将无效。

此外,没有理由为此使用本机查询,并且您不应该在参数周围加上括号:

@Query("SELECT l1 FROM Location l1 WHERE l1.node.id IN :ids")
List<Location> findLocationsByNodeIds(@Param("ids") Set<String> ids);

【讨论】:

非常感谢!这就是我一直在寻找的。我使用了 Set 因为我的 Node Java 类将标识符声明为 long。我已经编辑了问题以包含解决方案。我使用 nativeQuery 是因为我需要将聚合函数 MAX 与 INNER JOIN 一起使用,而且我不知道是否可以在没有 nativeQuery 选项的情况下执行此操作。再次感谢!

以上是关于是否可以在 Spring Repository @Query 注释中使用 Array 对象作为参数?的主要内容,如果未能解决你的问题,请参考以下文章

Spring Data + MongoDB GridFS 可以通过 Repository 访问吗?

Spring Data JPA Repository Method Query 用like?

扩展 CrudRepository (Spring) 时是不是需要 @Repository 注释?

是否可以在 Spring 中从非事务方法调用事务方法?

一个类可以同时注释为@Repository 和@Entity 吗?

Spring @Repository 最佳实践