从Spring Data @Query

时间:2018-02-26 10:25:34

标签: spring-data spring-data-jpa jpql

我正在编写一份调查问卷应用程序(Java,Spring Boot,SQL),我有一个工作查询,用于返回指定问卷中数据库中每个答案的计数:

@Query(value = "SELECT new org.project.domain.AnswerCount(a.value, count(a)) FROM "
            + "Answer a WHERE a.questionnaire = :questionnaire GROUP BY a.value")
    List<AnswerCount> findAnswerCountByQuestionnair(@Param("questionnaire") Questionnaire questionnaire);

现在我想要做的是将这些AnswerCounts按其回答的问题分组,并将其存储在QuestionResponseData对象列表中。我可以通过一些流分组方法在Java代码中完成它,但我更愿意直接在查询中进行速度。

这是否可能,最好的方法是什么?

以下是模型的相关部分:

public class AnswerCount {
    private String answer;
    private long count;
}

public class QuestionResponseData {

    private String question;
    private String type;
    private List<AnswerCount> answers;
}

/**
 * A Answer.
 */
@Entity
@Table(name = "answer")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "answer")
public class Answer implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @NotNull
    @Column(name = "jhi_value", nullable = false)
    private String value;

    @ManyToOne
    private Question question;

    @ManyToOne
    private Respondant respondant;

    @ManyToOne
    private Questionnaire questionnaire;
}

/**
 * A Question.
 */
@Entity
@Table(name = "question")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "question")
public class Question implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

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

    @Enumerated(EnumType.STRING)
    @Column(name = "jhi_type")
    private QuestionType type;

    @OneToMany(mappedBy = "question")
    @JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<Answer> answers = new HashSet<>();

    @ManyToMany(mappedBy = "questions")
    @JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<Questionnaire> questionnaires = new HashSet<>();
}

我正在思考类似的事情:

@Query(value = "SELECT new QuestionResponseData(q.text, q.type, answers) FROM "
+ "(SELECT new org.project.domain.AnswerCount(a.value, count(a)) as answerCount FROM "
+ "Answer a WHERE a.questionnaire = :questionnaire GROUP BY a.value") answers, "
+ "Question q WHERE answers.answerCount.question = q "
+ "GROUP BY answerCount.question")

但这显然不起作用......

有可能吗?

0 个答案:

没有答案