我有一个问题 - 我是hibernate的新手,需要转换一个由executing session.createSQLQuery(query).list()
命令返回的表。
我试图添加addEntity(Result.class)
命令,但程序抛出异常:
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.MappingException: Unknown entity: com.hib.entities.Result
我在mysql中的结果表如下所示:
| bookName | authorSurname | authorFirstName | authorPatronymic | releaseDate | amountBooks|
我试图创建Entity类Result并对其进行注释,但似乎我失败了。 我的实体类看起来像这样:
package com.hib.entities;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class Result {
String bookName;
String authorSurname;
String authorFirstName;
String authorPatronymic;
Integer releaseDate;
Integer amountBooks;
public Result(String bookName, String authorSurname, String authorFirstName, String authorPatronymic, Integer releaseDate, Integer
amountBooks) {
this.bookName = bookName;
this.authorSurname = authorSurname;
this.authorFirstName = authorFirstName;
this.authorPatronymic = authorPatronymic;
this.releaseDate = releaseDate;
this.amountBooks = amountBooks;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public void setAuthorSurname(String authorSurname) {
this.authorSurname = authorSurname;
}
public void setAuthorFirstName(String authorFirstName) {
this.authorFirstName = authorFirstName;
}
public void setAuthorPatronymic(String authorPatronymic) {
this.authorPatronymic = authorPatronymic;
}
public void setReleaseDate(Integer releaseDate) {
this.releaseDate = releaseDate;
}
public void setAmountBooks(Integer amountBooks) {
this.amountBooks = amountBooks;
}
public String getBookName() {
return bookName;
}
public String getAuthorSurname() {
return authorSurname;
}
public String getAuthorFirstName() {
return authorFirstName;
}
public String getAuthorPatronymic() {
return authorPatronymic;
}
public Integer getReleaseDate() {
return releaseDate;
}
public Integer getAmountBooks() {
return amountBooks;
}
@Override
public String toString() {
return "Result{" +
"bookName='" + bookName + '\'' +
", authorSurname='" + authorSurname + '\'' +
", authorFirstName='" + authorFirstName + '\'' +
", authorPatronymic='" + authorPatronymic + '\'' +
", releaseDate=" + releaseDate +
", amountBooks=" + amountBooks +
'}';
}
}
你能帮我解决这个问题吗?
答案 0 :(得分:2)
您必须区分session.createQuery(query)
和session.createSQLQuery(query)
如果您使用session.createQuery(query)
,您的查询将以HQL
(与SQL非常相似)编写,您可以这样做
Query q = session.createQuery(query)
List<Result> myResultList = q.list();
但是
如果您想使用session.createSQLQuery(query)
,则必须使用此
List<Result> myResultList = session.createSQLQuery(query).setResultTransformer(
Transformers.aliasToBean(Result.class)).list();
我个人建议你使用session.createQuery(query)
,这样你就可以受益于hibernate映射的优点
在这个link中,您将找到有关Hibernate上下文中HQL与SQL之间差异的更多解释。