JPA 存储库和带有可变参数的构造函数

JPA Repository and constructor with varargs

可以在@Query (org.springframework.data.jpa.repository) 中使用可变参数的构造函数。我的意思是 class 像这样:

public class EntityDTO {

  public EntityDTO(Long id, LocalDate... dates) {
    // some code here where dates 
    //which are converted to List<Pair<LocalDate, LocalDate> datesList
  }
}

public interface CustomRepository extends JpaRepository<Entity, Long> {

  @Query("SELECT new package.path.EntityDTO(id, date1, date2, date2) FROM Entity")
  List<EntityDTO> findEntityList();
}

现在出现这样的错误:

Unsatisfied dependency expressed through constructor parameter 3
 Validation failed for query for method public abstract java.util.List CustomRepository.findEntityList(java.lang.Long,java.time.LocalDate,java.time.LocalDate)

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: 
 Unable to locate appropriate constructor on class [EntityDTO]. Expected arguments are: long, java.time.LocalDate, java.time.LocalDate, java.time.LocalDate, java.time.LocalDate

这只是查询示例,因为dto在构造函数中可以有从2到12-14的id和LocalDate参数,日期可以来自不同的表(实体)。这取决于查询。为此,我希望 class 更通用。查询比这个例子复杂得多,但我对某种构造函数感兴趣,它使我有可能创建与我在评论中的 EntityDTO 构造函数中描述的类似的东西。可以在 @Query?

中使用可变参数

编辑: 如果 JPQL 没有此功能,您有什么建议我可以使用什么?

恐怕这是不可能的。

Hibernate 实现匹配构造函数解析的方式,只有参数数量与传递到构造函数表达式中的参数数量完全相同的构造函数才被视为潜在匹配。

解决方法可能是创建一个接受列表的构造函数,然后将您的查询修改为SELECT NEW EntityDTO(id, NEW list(date1, date2, date2))...如果仅嵌套NEW 支持表达式。不幸的是,这是一个长期存在的 feature request