【发布时间】: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 来完成这项工作。
【问题讨论】:
标签: spring postgresql spring-data-jpa