我花了两天时间试图解决这个问题。我有测试实体:
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "is_multichoice", nullable = false)
private boolean isMultichoice;
@Column(name = "is_open", nullable = false)
private boolean isOpen;
@Column(name = "picture")
private String picture;
@Column(name = "question")
private String question;
@ManyToOne
@JoinColumn(name = "test_id", nullable = false)
private Test test;
@Column(name = "archived", nullable = false)
private boolean isArchived;
@OneToMany(mappedBy = "question", fetch = FetchType.EAGER)
private Set<Answer> answers;
此测试实体有问题集,这样问题实体有答案集。< / p>
问题实体:
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "answer_text", nullable = false)
private String answerText;
@Column(name = "mark", nullable = false)
private int mark;
@ManyToOne
@JoinColumn(name = "question_id")
private Question question;
@Column(name = "picture")
private String picture;
@Column(name = "archived", nullable = false)
private boolean isArchived;
回答实体:
@NamedQuery(name = "getCurrentTestById",
query = "SELECT test From Result result JOIN result.test test JOIN result.user user " +
"JOIN test.questions question JOIN question.answers answer " +
"WHERE test.id = :testId AND user.id = :userId " +
"AND result.permission.id = :permissionId AND question.isArchived = false AND answer.isArchived = false")
然后,我的目标是从数据库中获取测试。我用条件写了HQL查询:问题和答案不应该存档。这是:
query = "SELECT t.id, t.test_name, t.duration, q.id as qId, " +
"q.question as question, q.is_multichoice as is_multichoice, " +
"q.is_open as is_open, a.id as aId, a.answer_text as answer_text FROM result r " +
"JOIN test t ON r.test_id = t.id " +
"JOIN user u ON r.user_id = u.id " +
"JOIN question q ON t.id = q.test_id JOIN answer a ON q.id = a.question_id " +
"WHERE t.id = :testId AND u.id = :userId AND r.permission = :permissionId " +
"AND q.archived = false AND a.archived = false", resultClass = com.bionic.entities.Test.class)
然而,这个查询仍然归还了我甚至存档的问题/答案。然后,我尝试编写本机SQL查询:
{{1}}
宾果!我在MYSQL工作台中测试了这个并且有效,我只获得了归档记录。但是,当我将它用于我的实体存档的问题和答案仍然出现!
我需要解决这个问题,而不是创建包装器和方法(在Java中)来从所有人那里获取未归档的记录。所以,我希望从查询中获得我需要的东西。
答案 0 :(得分:1)
如果您的具体测试可以存档但不存档 - 您的HQL不正确。 Hibernate找到一个包含一个或多个未归档问题的测试,然后加载测试获取所有问题(存档或未存档)。因此,您需要查询问题列表。像这样的东西
from Question question inner join question.test test WHERE test.id = :testId AND question.archived = false