如何在注释中使用元素实现 idbag?

How do I implement idbag with element in annotations?

我正在进行重构,我必须将我的 classes 从休眠 xml 更改为注释(首选 JPA 注释,但可以休眠)。我的一个实体使用 hibernate idbag 功能结合元素功能和连接 table.

休眠 xml:

<class name="com.my.package.EntityA" table="table_a">
        <id name="id" column="table_a_id" type="long" unsaved-value="null">
        <generator class="sequence">
            <param name="sequence">table_a_seq</param>
        </generator>
        </id>
        <idbag name="entityBIds" table="table_a_b" cascade="all" lazy="false">
        <collection-id column="table_a_b_id" type="long">
            <generator class="org.hibernate.id.SequenceGenerator">
                <param name="sequence">table_a_b_seq</param>
            </generator>
        </collection-id>
        <key column="fk_table_a_id" />
        <element column="fk_table_b_id" type="long"/>
    </idbag>
</class>

class 看起来像这样:

public class EntityA {

    Long id;

    Collection<Long> entityBIds;
}

架构:

table_a
    table_a_id number(13,0)

table_b
    table_b_id number(13,0)

table_a_b
    table_a_b_id number(13,0)
    fk_table_a_id number(13,0)
    fk_table_b_id number(13,0)

我将如何使用注释来实现它?请注意,这是一个非常复杂的系统,我想尽量减少除注释之外必须进行的更改。

您想要的是具有连接 table 的 one-to-many 关系。 请参见 https://en.wikibooks.org/wiki/Java_Persistence/OneToMany §1.5 加入 Table

您的 table 模型对 tables table_atable_a_b 都不实用。但我想改变它会很昂贵。

我希望您的 java 模型更灵活... 仅使用 Long id 定义 EntityB。在 EntityA 中有一个 Collection<EntityB> entityBs 并调整您的 getEntityBIds / setEntityBIds / addEntityBId 等的实现以访问它并根据需要进行转换。当然希望字段 entityBIds 是私有的,因此不会在实体外部使用。

我找到了答案!

@ElementCollection(targetClass = Long.class, fetch = FetchType.EAGER)
@CollectionTable(name = "TABLE_A_B", joinColumns = @JoinColumn(name="fk_table_b_id"))
@Column(name = "fk_table_a_id")
private Collection<Long> entityBIds;

当然这样做并不优雅,但我需要最简单的方法来转换为注释,而不会破坏实体周围的复杂代码。