我有两个hibernate类TestAuthor和TestBook,如下面的代码所示。我在表格中插入了一些记录,并成功插入。为确保记录正确插入,我使用了以下内容 SQL命令
SELECT * from TESTAUTHOR;
SELECT * from afk_owner.TestBook;
我现在想要使用下面的PrintAll部分中显示的Hibernate命令显示表testbook的内容。当我运行方法PrintAll时,我收到一个异常读取:
cannot be cast to msc.hibernate.persistence.TestBook
为什么我会发现这个错误以及如何解决它。?
PrintAll :
private void printAll() {
for (TestBook book : (List<TestBook>) HibernateUtil.getCurrentSession().createSQLQuery("SELECT * from afk_owner.testbook").list()) {
System.out.println(book.getmISBN() + ", " + book.getmTitle() + " " + (book.getAuthor()));
}
}
TestAuthor :
@Entity @Table(schema = "afk_owner", name = "testauthor")
public class TestAuthor {
@Id
@Column(name = "authorid")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequencegen")
@SequenceGenerator(name = "sequencegen", sequenceName = "afk_owner.testauthor_seq", allocationSize = 1)
private Integer mAuthorID;
@Column(name = "FNAME")
private String mFName;
@Column(name = "LNAME")
private String mLName;
@OneToMany(mappedBy = "author")
private List<TestBook> books;
public Integer getmAuthorID() {
return mAuthorID;
}
public void setmAuthorID(Integer mAuthorID) {
this.mAuthorID = mAuthorID;
}
public String getmFName() {
return mFName;
}
public void setmFName(String mFName) {
this.mFName = mFName;
}
public String getmLName() {
return mLName;
}
public void setmLName(String mLName) {
this.mLName = mLName;
}
public TestAuthor() {
// TODO Auto-generated constructor stub
}
}
TestBook :
@Entity @Table(schema = "afk_owner", name = "testbook")
public class TestBook {
@Id
@Column(name = "ISBN")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequencegen")
@SequenceGenerator(name = "sequencegen", sequenceName = "afk_owner.testbook_seq", allocationSize = 1)
private Long mISBN;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "authorid")
private TestAuthor author;
@Column(name = "title")
private String mTitle;
public Long getmISBN() {
return mISBN;
}
public void setmISBN(Long mISBN) {
this.mISBN = mISBN;
}
public TestAuthor getAuthor() {
return author;
}
public void setAuthor(TestAuthor author) {
this.author = author;
}
public String getmTitle() {
return mTitle;
}
public void setmTitle(String mTitle) {
this.mTitle = mTitle;
}
public TestBook() {
// TODO Auto-generated constructor stub
}
}
答案 0 :(得分:0)
使用Hibernate API和本机SQL是不可能的。没有类型控制,所以你必须强制转换。 击>
根据{{3}}有可能,但在Session Api docs中可以省略它。您必须弄清楚如何使用它来满足您的需求。由于这些解决方案被标记为已弃用,因此您应该完全避免使用它。您应该尝试转移到JPA并使用Hibernate作为其实现。
如果你想使用HQL,它可以工作。查询将是这样的:
Query<TestBook> query=session.createQuery("SELECT tb FROM TestBook tb WHERE tb.author.mAuthorID=:owner",TestBook.class);
query.setParameter("author",authorId);
List<TestBook> books=query.list();
您只需调整属性名称(tb,作者,id属性)等以满足您的需求,但您可以了解如何使用它。