2012-06-16 94 views
2

晚上好!休眠HQL映射异常列名

我一直在学习和部分使用hibernate一段时间,并且遇到了使用hql连接的麻烦。

我跟着这些指令只为实践,看看它甚至还可以...
http://www.java2s.com/Tutorial/Java/0350__Hibernate/HSQLJoinTwoClasses.htm

他基本上产生3类: 供应商,产品,软件
一个供应商有很多产品 许多产品一个供应商

一切工作得很好...除了我不能理解一个特定的事情,阻止我实现到我自己的代码。 这是我无法理解的部分:

<class name="Product"> 

    <id name="id" type="int"> 
     <generator class="increment"/> 
    </id> 

    <property name="name" type="string"/> 
    <property name="description" type="string"/> 
    <property name="price" type="double"/> 

    <many-to-one name="supplier" class="Supplier" column="supplierId"/> 
</class> 


<class name="Supplier" > 
    <id name="id" type="int"> 
    <generator class="increment"/> 
    </id> 

    <property name="name" type="string"/> 
    <bag name="products" inverse="true" cascade="all,delete-orphan"> 
    <key column="supplierId"/> 
    <one-to-many class="Product"/> 
    </bag> 

</class> 

The query would be: 
SELECT s.name, p.name, p.price 
    FROM Product p INNER JOIN p.supplier AS s"; 

他为什么使用“供应商ID”为列的值时,有没有到处定义供应商ID。我无法弄清楚在后台发生了什么,或者为什么它在工作...

我一直在寻找一个年龄的解释..希望你们中的一些人做了一些这样的经验,可以帮助我。会很棒。希望我不太模糊。

有一个愉快的一天, 迈克尔Kargl


解决方案

问题是,我错过了在数据库中的实际外键列名为供应商ID ...

create table Product(
     id int, 
     name varchar, 
     description varchar, 
     price decimal(6,2), 
     >>>> supplierid int <<<<< 
) 

(我永远不会复制和粘贴这样的代码再次..)
其余大部分由@carbontax's post@MikkoMaunu's post

回答

2

你说supplierId没有定义,但它是。

当您在产品定义中编写<many-to-one name="supplier" class="Supplier" column="supplierId"/>时,您将supplierId定义为Product类中的字段。

在Supplier类中,您告诉Hibernate,对于products集合,Product类中外键的名称是supplierId

当您执行您的HQL语句时,Hibernate会将这些信息转换为“ON p.supplierId = s.id”sql子句。

+0

Awww我怎么可能错过了这个.. 你现在已经知道我现在有多尴尬。 永远不会少..感谢您的好解释! 它让一些事情变得更清晰!谢谢! –

2

在列的

<many-to-one name="supplier" class="Supplier" column="supplierId"/> 

值定义在产品表的外键列的名称。外键包含供应商表的一些主键值。 本专栏将实现数据库中产品与供应商之间的关系。没有这样的专栏,数据库中的产品和供应商之间就没有关系。然后Bag就是这个关系的反面。

类似的情况可以从Hibernate documentation找到。

+0

感谢您的好解释!尴尬,我错过了“细节”..但感谢您的伟大解释!简短而清楚..我不知何故真的很困惑;)谢谢你们两位!祝你今天愉快! –