Search code examples
apacheentity-relationshipapache-cayenne

Apache Cayenne 1-M relationship within same table


I am building a system that allows elements or landing spaces to be dragged onto other landing spaces. As such the model will be a tree of landing spaces with elements at the leaf.

I wish to use apache cayenne to store this data. An ideal situation would be to invoke LandingSpace.getChildren() on a cayenne "LandingSpace" class and retrieve the children, which contains landing spaces and/or elements.

Essentially I wish to make a 1-M relationship from a table to itself. Is there a way in which this can be achieved?

Many thanks


Solution

  • Sure. Relationship to self is just another relationship in Cayenne. Start with this table model:

    LANDING_SPACE
       ID        # PK
       PARENT_ID # FK to parent
       ...       # other columns
    

    And map a pair of relationships over the ID/PARENT_ID join: "parent" (to one) and "children" (to many)