gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:16:39 24 4
gpt4 key购买 nike

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

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 .

关于java - JPA 存储库和带有可变参数的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49954502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com