Spring Data Jpa 我不能在JPQL查询中调用另一个构造函数中的构造函数,什么是有效的解决方法?

xjreopfe  于 2023-08-05  发布在  Spring
关注(0)|答案(1)|浏览(133)

似乎我不能在JPQL查询中调用另一个构造函数中的构造函数,如下所示

TypedQuery<QuestionCommentResponseDto> = entityManager.createQuery("""
            SELECT new QuestionCommentResponseDto (
            qc.id, q.id, qc.createdDate, qc.modifiedDate, qc.text, new AccountResponseDto(
                a.id, a.username
                )
            ) FROM QuestionComment qc JOIN FETCH Question q JOIN FETCH Account a
            WHERE qc.id = :id
        """, QuestionCommentResponseDto.class)

字符串

*****像qc.text, (SELECT new AccountResponseDto(a.id, a.username)这样的子查询也不起作用(qc.text之后的部分有问题)。IDE说

需要'(',,FUNCTION或标识符,得到'('我应该简单地查询一个DTO,然后查询另一个吗?
一点背景

@Override
    public Optional<QuestionCommentResponseDto> getByQuestionCommentId(Long questionCommentId) {
    // the query goes here

x

// I can make it a regular class if it's necessary
public record QuestionCommentResponseDto(Long id, Long questionId, LocalDateTime createdDate,
                                         LocalDateTime modifiedDate, String text, AccountResponseDto owner) {}
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "question_comments")
public class QuestionComment {

    @Setter(AccessLevel.NONE)
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false, updatable = false)
    private Long id;

    @Setter(AccessLevel.NONE)
    @NotNull
    @CreatedDate
    @Column(name = "created_date", nullable = false)
    private LocalDateTime createdDate;

    @Setter(AccessLevel.NONE)
    @NotNull
    @LastModifiedDate
    @Column(name = "modified_date", nullable = false)
    private LocalDateTime modifiedDate;

    @NotBlank
    @Column(name = "text", nullable = false)
    private String text;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "account_id", nullable = false, updatable = false)
    private Account owner; // includes the fields id and username

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "question_id", nullable = false, updatable = false)
    private Question question; // includes the id field

的字符串
如果我省略了一些重要的代码部分,请告诉我(在我看来,在这种情况下根本不需要代码,因为这不是一个调试问题)

lhcgjxsq

lhcgjxsq1#

你能在你的数据库中创建一个SQL视图甚至实体化视图吗?
然后,您可以有一个实体(在您的视图上)来支持基于JPA接口的投影。
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections.interfaces
使用Spring Data,您可以像查询表一样查询物化视图。
我会尊重关注点分离并创建一个@Component
将实体Map到所需的业务对象(Dto)。

相关问题