3.4.6.2.3. Bidirectional association with indexed collections


A bidirectional association where one end is an indexed collection (ie. represented as a @IndexColumn, @org.hibernate.annotations.MapKey or @org.hibernate.annotations.MapKeyManyToMany) requires special consideration. If a property on the associated class explicitly maps the indexed value, the use of mappedBy is permitted:
@Entity
public class Parent {
    @OneToMany(mappedBy="parent")
    @org.hibernate.annotations.IndexColumn(name="order")
    private List<Child> children;
    ...
}

@Entity
public class Child {
    ...
    //the index column is mapped as a property in the associated entity
    @Column(name="order")
    private int order;

    @ManyToOne
    @JoinColumn(name="parent_id", nullable=false)
    private Parent parent;
    ...
}
Copy to Clipboard Toggle word wrap
But, if there is no such property on the child class, we can't think of the association as truly bidirectional (there is information available at one end of the association that is not available at the other end: the index). In this case, we can't map the collection as mappedBy. Instead, we could use the following mapping:
@Entity
public class Parent {
    @OneToMany
    @org.hibernate.annotations.IndexColumn(name="order")
    @JoinColumn(name="parent_id", nullable=false)
    private List<Child> children;
    ...
}

@Entity
public class Child {
    ...
    @ManyToOne
    @JoinColumn(name="parent_id", insertable=false, updatable=false, nullable=false)
    private Parent parent;
    ...
}
Copy to Clipboard Toggle word wrap
Note that in this mapping, the collection-valued end of the association is responsible for updating the foreign key.
Back to top
Red Hat logoGithubredditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust. Explore our recent updates.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

Theme

© 2025 Red Hat