gpt4 book ai didi

spring - 使用 @ElementCollection 的查询的 DTO 投影导致 'Unable to locate appropriate constructor on class' 错误

转载 作者:行者123 更新时间:2023-12-02 06:40:29 26 4
gpt4 key购买 nike

当需要来自 Antity 的几个字段并使用 Fetch 连接时,我正在使用投影编写自定义查询,以减少一个 session 中的查询量。不幸的是,当返回的 dto 中的类型是集合时,遇到了问题。

我有以下带有 @ElementCollection 的类(用于此目的的简化版本):

@Entity
class MyClass(

val someString: String,

@ElementCollection
@Enumerated(EnumType.STRING)
var enums: MutableSet<Enum>,

@ManyToOne
var condition: Condition

//And so on...
)

以及用于投影的 DTO:

data class ProjectionDTO(
val aString: String,
val enumList: List<Enum>
)

但是当使用查询时:

fun query(condition: Condition): List<ProjectionDTO> =
entityManager.createQuery(
"""SELECT NEW com.xxx.ProjectionDTO( m.someString, e ) FROM MyClass m
INNER JOIN FETCH m.enums e
WHERE m.condition = :condition""", ProjectionDTO::class.java)
.setParameter("condition", condition)
.resultList
}

我收到以下异常:

Exception:[org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [com.xxx.ProjectionDTO]. Expected arguments are: com.xxx.String, com.xxx.Enum [SELECT NEW com.xxx.ProjectionDTO( m.someString, e ) FROM MyClass m
INNER JOIN FETCH m.enums e
WHERE m.condition = :condition]]

已经尝试了不同类型的集合、附加构造函数和调用给定 @ElementCollection 的字段,如查询参数中的 e.enum 。是否可以从这种查询返回列表(或其他集合)?如果是这样,我该如何解决?

最佳答案

构造函数查询中不允许使用集合路径表达式。 link

仅将根实体放入构造函数中:

SELECT NEW com.xxx.ProjectionDTO(m) WHERE m.condition = :condition

在构造函数中将 m.enums、m.someString 分配给字段。

关于spring - 使用 @ElementCollection 的查询的 DTO 投影导致 'Unable to locate appropriate constructor on class' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55490416/

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