Kramer
Kramer

Reputation: 1078

How do I implement idbag with element in annotations?

I'm working on a refactor where I have to change my classes from hibernate xml to annotations (JPA annotations preferred but hibernate okay). One of my entities uses the hibernate idbag feature combined with the element feature and a join table.

hibernate 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>

The class looks like this:

public class EntityA {

    Long id;

    Collection<Long> entityBIds;
}

Schema:

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)

How would I use annotations to implement this? Note that this is a pretty complex system and I want to minimize the changes that I have to make aside from the annotations.

Upvotes: 1

Views: 274

Answers (2)

Kramer
Kramer

Reputation: 1078

I discovered the answer!

@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;

Of course doing this is less than elegant, but I needed the simplest way to convert to annotations without breaking the complex code surrounding the entities.

Upvotes: 0

Florian H.
Florian H.

Reputation: 367

What you want is a one-to-many relation with a join table. See https://en.wikibooks.org/wiki/Java_Persistence/OneToMany §1.5 Join Table

Your table model is not practical with both tables table_a and table_a_b. But changing it would be costly I guess.

I hope your java model is more flexible... Define an EntityB with only a Long id. In EntityA have a Collection<EntityB> entityBs and adapt the implementation of your getEntityBIds / setEntityBIds / addEntityBId / etc. to access it and convert as required. Of course hoping the field entityBIds was private and thus not used outside the entity.

Upvotes: 1

Related Questions