mjs
mjs

Reputation: 22409

Hibernate mappedBy in aggregate associations, possible to use?

I am trying to figure out mappedBy ... If I have a Person { Address address; } then I can add a Person person in Address with mappedBy "address"... However, if Person has class Person { PersonDetails personDetails } and PersonDetails { Address address } then is there a way to do a mappedby back to the Person from Address ? How can I achieve this?

This setup is what is commonly used and works fine:

    class Person {
            @OneToOne
            Address address;
    }


    class Address {
            @OneToOne(mappedBy="address")
            Person person;
    }

The above will allow for person to automatically be set on Address when when new Person() is called.

However, can I do something along these lines, if so how? The below example doesn't work:

    class Person {
            @OneToOne
            PersonDetails personDetails;
    }

    class PersonDetails {
            @OneToOne
            Address address;
    }

    class Address {
            @OneToOne(mappedBy="IS THERE A WAY TO REFER TO THE PERSON THROUGH MY OWNER, PERSONDETAILS??")
            Person person;
    }

Do I have to manually set the person on Address when creating a new Person().

Is it possible to use @Column(table, or @JoinColumn in combination somehow?

Upvotes: 0

Views: 48

Answers (2)

mjs
mjs

Reputation: 22409

Not possible using Hibernate or JPA.

Upvotes: 0

Predrag Maric
Predrag Maric

Reputation: 24433

mappedBy is used to mark the other side of bidirectional relationship between two entities. So, it is not intended for the purpose you describe.

If you just want to access Person from Address, you can just do this

class Address {
    @OneToOne(mappedBy = "address")
    PersonDetails personDetails;
    ...
    public Person getPerson() {
        return personDetails == null ? null : personDetails.getPerson();
    }
}

Upvotes: 1

Related Questions