【问题标题】:Mapping in Hibernate on another field than the PK在 Hibernate 中映射到 PK 以外的另一个字段
【发布时间】:2016-10-21 17:34:14
【问题描述】:

我现在被困了一会儿,我需要一些帮助。

我想在两个表中的任何一个中都不是 PK 的 2 个字段之间在休眠中进行映射

Table Category (
   catId   Numeric(10),
   categoryBusinessRef  Numeric(10)
)


Table Product (
   productId    Numeric(10),
   categoryBusinessRef  Numeric(10)
)

Sql 查询是:

SELECT * 
   from Category  as a 
   Join Product  as b on a.categoryBusinessRef = b.categoryBusinessRef  

但在 Hibernate 中,它让我有了这个映射

SELECT * 
   from Category  as a 
   Join Product  as b on a.categoryId = b.categoryBusinessRef

我的hbms看起来很喜欢

<class name="Category" table="A">
        <id name="categoryId" length="10">
            <column name="categoryid" />
            <generator class="sequence">
                <param name="sequence">S_category</param>
            </generator>
        </id>
        <set  name="categoryBusinessRefs" table="B" >
            <key>
                <column name="categoryBusinessRef" />
            </key>
            <one-to-many class="ProductClass" />
        </set>
</class>

<class name="Product" table="B">
        <id name="productId" length="10">
            <column name="productid" />
            <generator class="sequence">
                <param name="sequence">S_product</param>
            </generator>
        </id>
        <property name="categoryBusinessRef" length="10">
            <column name="categoryBusinessRef" />
        </property>
</class>

所以这是一个一对多的关系,但它必须与另一个值作为类别的 PK 进行映射

感谢您的帮助

编辑:

如果我做不到,那好吧!但是如果我可以这样做,我知道所有带有主键的东西,但我的问题不是“在 Hibernate 中映射到 PK”而是“在 Hibernate 中映射到另一个字段而不是 PK”,所以说地图的答案我对PK不感兴趣:p

【问题讨论】:

  • 我猜 Table A 是 OneToMany-Relation 的 1 端,对吗?那么,表A中的属性disc是错误的。
  • 我没有选择我认为的商品名称,我将重命名那些变量
  • 这不是名字好坏的问题。我的假设正确吗?
  • 是的,它是正确的,但这些不是唯一的
  • 确实是多对多

标签: java hibernate mapping one-to-many hibernate-onetomany


【解决方案1】:

你的模型是错误的,除非你想要一个笛卡尔积(这是一个罕见的要求)你应该总是通过主键加入。

您可以有一对一、一对多或多对多的关系(后两种更常见)。

在一对多中,您需要one 一侧的pk 到many 一侧。

在多对五中,您需要一个关系表来进行映射。

假设您希望有很多 B 连接到同一个 A(所以是一对多)。

CREATE TABLE a (
  id   NUMERIC(10) PRIMARY KEY,
  disc NUMERIC(10) NOT NULL
)

CREATE TABLE b (
  id    NUMERIC(10) PRIMARY KEY,
  a_id  NUMERIC(10) NOT NUL REFERENCES a (id)
)

现在可以查询了

SELECT * 
FROM a 
JOIN b ON b.a_id = a.id

并从a 恢复所有与所有b 具有适当关系的磁盘。

【讨论】:

  • 是的,但是由于数据库的历史记录,我需要映射到其他字段,每次更新都需要一个新记录,因此行的 ID 和业务数据表示的 ID
  • 但在很多情况下,您必须映射到某些不是主键的值(以大数据为例)
  • @GillesBodart PK 必须唯一标识元组,因此所有映射都由 PK 完成,您应该只对非 PK 字段应用限制操作。大数据不一定使用关系数据库。
  • 我知道,但我的问题不是这样做是否好:) 我的问题是如何做到这一点;-)
  • @GillesBodart 让我们知道您是如何在不更改表结构的情况下使其工作的(添加索引包括在内)。
猜你喜欢
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多