我的应用程序出现了一个奇怪的错误.
我正在尝试使用session.createCriteria().list()从数据库(MySQL)中检索实体列表,但是我得到了这个org.hibernate.WrongClassException.
我查了这个错误,我知道这意味着什么,但我不知道如何在我的上下文中解决它.
我有以下数据库结构:
CREATE TABLE vtiger_crmentity (
`crmid` int(19) NOT NULL
)
CREATE TABLE vtiger_account (
`accountid` int(19) NOT NULL DEFAULT 0
)
CREATE TABLE vtiger_accountscf (
`accountid` int(19) NOT NULL DEFAULT 0
)
CREATE TABLE vtiger_accoutshipads (
`accountaddressid` int(19) NOT NULL DEFAULT 0
)
CREATE TABLE vtiger_accountbillads (
`accountaddressid` int(19) NOT NULL DEFAULT 0
)
因此,快速解释,所有表都通过这些id列链接,在最后一级,vtiger_accountscf表有1个vtiger_accountshipads和1个vtiger_accountbillads.所有表都具有相同的PK.
所以我创建了这样的类(存根):
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "vtiger_crmentity")
public class VtigerCrmentity {
@Id
@Basic(optional = false)
@Column(name = "crmid", nullable = false)
public Integer getId() {
return this.id;
}
}
@Entity
@PrimaryKeyJoinColumn(name = "accountid")
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "vtiger_account")
public class VtigerAccount extends VtigerCrmentity {
}
@Entity
@PrimaryKeyJoinColumn(name = "accountid")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "vtiger_accountscf")
public class VtigerAccountscf extends VtigerAccount {
}
@Entity
@PrimaryKeyJoinColumn(name = "accountaddressid")
@Table(name = "vtiger_accountbillads")
public class VtigerAccountbillads extends VtigerAccountscf {
}
@Entity
@PrimaryKeyJoinColumn(name = "accountaddressid")
@Table(name = "vtiger_accountshipads")
public class VtigerAccountshipads extends VtigerAccountscf {
}
这是我的问题.当我做:
getSession().createCriteria(VtigerAccountbillads.class).list();
我得到了例外:
org.hibernate.WrongClassException: Object with id: 11952 was not of the specified subclass: VtigerAccountbillads (loaded object was of wrong class class VtigerAccountshipads)
at org.hibernate.loader.Loader.instanceAlreadyLoaded(Loader.java:1391)
at org.hibernate.loader.Loader.getRow(Loader.java:1344)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:611)
at org.hibernate.loader.Loader.doQuery(Loader.java:829)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
at org.hibernate.loader.Loader.doList(Loader.java:2533)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
at org.hibernate.loader.Loader.list(Loader.java:2271)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1716)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
根据项目限制,我没有使用spring或类似配置Hibernate并创建会话.
我的地图错了吗?
解决方法:
你能说出你在DB中有哪些数据记录?
看来不同表之间的id具有相同的值,所以当hibernate试图加载具有特定id的实体时,如果内存中已经存在另一个具有相同id的实体,那么hibernate就会抱怨这个问题.