theFriedC
theFriedC

Reputation: 430

Hibernate: Get Parent for OneToMany-Child Entity Without Bidirectional Relation

how can i check if an entity has a parent entity which maps this entity over @OneToMany annotation. The mapping is unidirectional defined on the parent

@Entity
public class ParentEntity {

    ...

    @OneToMany(cascade=CascadeType.ALL)
    private Collection<ChildEntity> childEntities;

    ...

Hibernate automagically creates a mapping table, or if used @JoinColumn a column with the parent-id in the child table. When the child gets persisted, hibernate adds the corresponding parent id to the db-table.

I do not want to define a bidirectional relation since i do not need this "feature" in my application-logic and there are already loads of entities which would need a change. I just need the parent for replication issues. This means i have to export some data to another DB schema (has different table structure).

I use an interceptor to trigger the replication action in the "onSave" method defined by the Interceptor interface. If a parent gets a new child, there is just the persist action of the child triggering. I do not know the parent it belongs to.

I really appreciate any help!

Thanks!

Upvotes: 4

Views: 3429

Answers (2)

theFriedC
theFriedC

Reputation: 430

I have found an answer to the problem without using queries.

The Interceptor interface of Hibernate defines three methods concerning collections.

If a collection on an entity (ParentEntity in this case) is changed one of the three methods is called:

public void onCollectionRecreate(Object collection, Serializable key)
        throws CallbackException {
}


public void onCollectionRemove(Object collection, Serializable key)
        throws CallbackException {
}

public void onCollectionUpdate(Object collection, Serializable key)
        throws CallbackException {
}

The object "collection" is then of a type PersistenceBag from which the "owner" can be read. That would be the parent in this case. Another hint: The second parameter of the methods is the hibernate key of the "owner". For my purpose i have got a configuration file which maps the Hibernate entities to the tables on the target system. In this configuration the parnent java class is defined.

Upvotes: 1

Firo
Firo

Reputation: 30813

int count = session.createCriteria(Parent.class)
    .createCriteria("childEntities")
    .add(Restrictions.eq(childIdInQuestion))
    .setProjetction(Projections.rowCount())
    .uniqueResult();

Boolean hasParent = count > 0;

Upvotes: 3

Related Questions