几周以来,我一直在使用 Hibernate。好吧,它是一个非常有用的工具,但我无法解决以下任务:
桌子:
Create Table `Product`
(
`product_id` INT(10) PRIMARY KEY,
`bundle_id` INT(10) NULL,
`product_type` VARCHAR(50) NOT NULL,
`title` VARCHAR(255) NOT NULL,
`desc` VARCHAR(255) NULL,
`price` REAL(10) NOT NULL,
...
);
在 Java 中我有 3 个类
@Entity
@Table(name = "Product")
@DiscriminatorColumn(name = "product_type")
public abstract class Product {
...
}
有两种类型的实例,其中“项目”可以但可能并不总是值得“捆绑”。“捆绑包”至少有一个“项目”
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorValue(value = "Item")
public class Item extends Product {
Bundle bundle;
....
@ManyToOne (fetch=FetchType.LAZY, targetEntity=Bundle.class)
@JoinColumn (name="bundle_id")
public Bundle getBundle() {...}
public void setBundle(Bundle bundle) {...}
....
}
和:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorValue(value = "Bundle")
public class Bundle extends Product {
Set<Item> items;
....
@OneToMany (mappedBy="bundle", targetEntity=Item.class)
@OrderBy ("list_nr")
public Set<Item> getItems() {...}
public void setItems(Set<Item> items) {...}
....
}
在运行时无法调用任何数据,错误:预期类型:org.blah.Bundle,实际值:org.blah.Item
有没有人有想法或提示。正在搜索谷歌上下,但我找不到这个特定问题。
不知道为什么 Hibernate 尝试这个:
Hibernate:
select
item0_.item_id as product1_7_,
item0_1_.price as price3_7_,
item0_1_.title as title4_7_,
item0_.bundle_id as bundle3_11_
from
Item item0_
inner join
Product item0_1_
on item0_.item_id=item0_1_.product_id
错误:
01.09.2013 00:36:49 org.hibernate.property.BasicPropertyAccessor$BasicSetter
set ERROR: HHH000123: IllegalArgumentException in class: org.blah.Item,
setter method of property: bundle 01.09.2013 00:36:49
org.hibernate.property.BasicPropertyAccessor$BasicSetter set ERROR: HHH000091:
Expected type: org.blah.Bundle, actual value: org.blah.Item 01.09.2013 00:36:49
org.blah.QueryMngr findAllItems SEVERAL: get failed
查找所有项目():
public static List<Item> findAllItems() {
log.debug("find all Item instances");
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.getTransaction().begin();
List<Item> items = session.createQuery("From Item").list();
//for (Item item : items) {
// Hibernate.initialize(item.getBundle());
//}
session.getTransaction().commit();
log.debug("get successful");
session.close();
return items;
} catch (HibernateException exc) {
if (session != null) {
session.getTransaction().rollback();
session.close();
}
log.error("get failed", exc);
throw new RuntimeException( exc.getMessage() );
}
}