我正在尝试从关联表(从具有多对多关系的2个表)中进行选择。这是我的实体:
问题:
@Entity
@Table(name = "question")
public class Question {
@Id
private int id;
@Column(name = "question_text")
private String text;
@Column(name = "chapter_id")
private int chapterId;
@ManyToMany(mappedBy = "questions")
@Transient
public Set<Assessment> assessments = new HashSet<Assessment>();
public Question(int id, String text, int chapterId) {
this.id = id;
this.text = text;
this.chapterId =chapterId;
}
//getters setters
评估:
@Entity
@Table(name = "assessment")
@Access(AccessType.FIELD)
public class Assessment {
@Id
private int id;
private String name;
@Column(name = "chapter_id")
private int chapterId;
private int grade;
private String type;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "assessment_question",
joinColumns = { @JoinColumn(name = "assessment_id") },
inverseJoinColumns = { @JoinColumn(name = "question_id") }
)
@Transient
@ElementCollection(targetClass=Question.class)
Set<Question> questions = new HashSet<Question>();
public Assessment(int id, String name, int chapterId, int grade, String type) {
super();
this.id = id;
this.name = name;
this.chapterId = chapterId;
this.grade=grade;
this.type=type;
}
//getters & setters
在MySQL模式中,这2个实体具有关联表Assessment_question,同时具有assessment_id
和question_id
作为键。
我正在尝试从该表中读取条目。这是DAO方法:
@Transactional
public List<Question> getQuestionsOfAssessment(int id) {
List<Question> list = null;
Configuration con = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Question.class);
SessionFactory sf = con.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
try{
TypedQuery<Question> query=sf.openSession().createQuery("select q from Question q join q.assessments a where a.id = :id");
query.setParameter("id",id);
list = query.getResultList();
tx.commit();
session.close();
}catch(Exception e){
e.printStackTrace();
}
return list;
}
但是,我收到以下异常:
java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: assessments of: models.Question [select q from models.Question q join q.assessments a where a.id = :id]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:133)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:713)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:103)
at dao.AssessmentQuestionDAO.getQuestionsOfAssessment(AssessmentQuestionDAO.java:60)
at webapp.Main.main(Main.java:156)
我在这里阅读了很多有关如何使用多对多以及如何解决此问题的信息,但到目前为止,没有任何解决方案。看来我正在丢失一些可能看不到的非常小的事情。您对如何解决这个问题有任何想法吗?