我想获得一些字段,然后将其设置为我的Test.entity。我的SQL查询:
query = "SELECT t.id as tId, 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)
测试实体:
public class Test {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "duration", nullable = false)
private int duration;
@Column(name = "test_name", nullable = false, unique = true)
private String testName;
@Column(name = "archived", nullable = false)
private boolean archived;
@OneToMany(mappedBy = "test", fetch = FetchType.EAGER)
private Set<Question> questions;
@ManyToMany(mappedBy = "tests")
private Set<User> users;
质询实体:
public class Question {
@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;
回答实体:
public class Answer {
@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;
然而,在执行此查询后,我得到了exeption:
Caused by: java.sql.SQLException: Column 'id' not found.
DAO.class:
public Test getCurrentTest(long id, long testId, long permissionId) {
Query query = em.createNamedQuery("getCurrentTestById");
query.setParameter("userId", id);
query.setParameter("testId", testId);
query.setParameter("permissionId", permissionId);
return (Test) query.getSingleResult();
}
我做错了什么?
答案 0 :(得分:3)
您的查询未返回名为id
的字段。它有名为aId, qId, and tId
的字段。
您需要在实体中使用正确的列名称。例如,在Test实体中,您声明了一个名为id的列。除了您的查询没有返回名为id的列,它返回一个名为tId的列。请参阅下文,了解需要更改的内容。
public class Test {
@tId
@Column(name = "tId")
@GeneratedValue(strategy = GenerationType.AUTO)
private long tId;
....