我有一个奇怪的问题,涉及从SQLLite DB获取对象。当我试图从列表中获取对象时,我得到以下错误:
Caused by: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to DataBase.Hibernate.Entities.Client.ClientEntity
有什么建议吗?
映射文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="DataBase.Hibernate.Entities.Client.ClientEntity" table="Clients">
<meta attribute="class-description">
This class contains the client detail.
</meta>
<id name="id" type="int" column="ID">
<generator class="native"/>
</id>
<property name="name" column="Name" type="string"/>
<property name="surname" column="Surname" type="string"/>
<property name="contact" column="Contact" type="string"/>
</class>
<sql-query name="ClientEntity.findByID">
<![CDATA[
select * from Clients AS c where c.ID =:id
]]>
</sql-query>
<sql-query name="ClientEntity.getAll">
<![CDATA[
select * from Clients
]]>
</sql-query>
</hibernate-mapping>
ClientEntity类:
package DataBase.Hibernate.Entities.Client;
import java.io.Serializable;
public class ClientEntity implements Serializable{
private int id;
private String name;
private String surname;
private String contact;
public ClientEntity(String name, String surname, String contact) {
this.name = name;
this.surname = surname;
this.contact = contact;
}
public ClientEntity() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
}
从表客户端获取对象的方法
HibernateManager hibernate = HibernateManager.beginWork();
List<ClientEntity> list = hibernate.getNamedQuery(
Queries.GET_CLIENT_BY_ID).setInteger(Columns.ID, aClientID).list();
hibernate.endWork();
Queries.GET_CLIENT_BY_ID 是一个变量,其中包含来自ClientEntity.hbm.xml文件(“ ClientEntity.findByID ”)的“命名查询”名称。
答案 0 :(得分:2)
您需要学习HQL,并使用它而不是使用SQL。您的2个查询应该是HQL查询:
select c from ClientEntity c where c.id =:id
select c from ClientEntity
请注意,firsqt查询无用,因为您只需要使用
session.get(ClientEntity.class, id)
通过其ID获取客户端。
答案 1 :(得分:0)
好的,我明白了。我做了小修正。但毕竟我遇到Null Pointer Exception的问题......
方法 listClients 中的课程 T4esty 出现问题。
属性 hibernate.connection.url 在程序启动时不可用,但在小型初始化后“动态”设置。每次程序启动时都会创建数据库。