【发布时间】:2020-05-25 00:17:42
【问题描述】:
我想在 HQL 查询中构造一个包含类的列表,但每当我尝试将列表传递给新类时,SQL 生成失败并告诉我 org.postgresql.util.PSQLException: ERROR: syntax error at or near "."。最终结果应该是一个 Form 对象列表,其中每个 Form 都包含一个投票列表。
如果我以SELECT new com.my.class.Projection(q.id, q.otherId, q.votes) 开始查询,q.votes 将在 SQL 中生成为.,这会导致错误。但是,如果我将 Projection 的投票列表更改为 int(并将查询更改为 SELECT new com.my.class.Projection(q.id, q.otherId, q.votes.size) 只是为了获取大小,它会告诉我大小是多少。为什么我可以检索投票数量,而不是列表本身?任何帮助将不胜感激!
将生成的部分SQL:
Hibernate: select question0_.id as col_0_0_, question0_.other_id as col_1_0_, . as col_2_0_ from public.questions`
源代码:
问题库
interface QuestionRepository : JpaRepository<Question, Long> {
@Query("SELECT new com.my.class.Projection(q.id, q.otherId, q.votes) FROM Question q WHERE q.form = :form")
fun findQuestionSimple(@Param("form") form: Form): List<Projection>
投影
data class Projection(
var id: Long = 0,
var otherId: String
) {
@OneToMany(mappedBy = "question")
var votes: List<VoteProjection>? = listOf()
constructor(id: Long, otherId: String, votes: List<Vote>) : this(id, otherId) {
this.id = id
this.otherId = otherId
this.votes = votes.map { VoteProjection(it.id, if (it.user !== null) VoteGuestProjection(it.user!!.id) else null) }
}
}
data class VoteProjection(
var id: Long = 0,
var user: VoteUserProjection?
)
data class VoteUserProjection(
var id: Long = 0
)
问题类
@Entity
@Table(name = "questions", schema = "PUBLIC")
class Question {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = 0
@NotNull
var otherId = ""
@ManyToOne
@JsonIgnore
@JoinColumn
var form: Form? = null
@OneToMany(mappedBy = "form")
@JsonIgnoreProperties("form")
var votes: List<Vote> = listOf()
}
投票类
@Entity
@Table(name = "votes", schema = "PUBLIC")
class Vote {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = 0
@ManyToOne
@JoinColumn
var user: User? = null // Not relevant for this question
}
【问题讨论】:
标签: java hibernate spring-boot kotlin spring-data-jpa