Recursive Entities in Hibernate

Tables can be related with themselves: the foreing key of the table points to the key of the table.

This bizarre thing is very useful when you want to represent data which is hierarchically dependent in the real world: an organization (with many departments and sub-departments depending one of each other), human organizations (a boss with his employees) or more complex structures (a network of offices who depend on local branches, and those branches depend on the general headquarters).

In the language of the databases, this could be represented as this:

And the table can be created with this command:

CREATE TABLE hg_struct
(
id_struct          BIGINT AUTO_INCREMENT PRIMARY KEY NOT NULL,
some_data        VARCHAR(255),
id_struct_parent   BIGINT,
);

Ok, I've didn't documented the foreing key reference to the same table. I don't care.

In Hibernate, this is documented as a one-to-many relationship where both tables are the same. Or as a many-to-one relationship where both tables are the same.

I've set both configurations (getParent() to access my parent in the herarchy and getChildren() to access my sons) because I need both are necessary.

Here is my example:

@Entity
@Table( name = "hg_struct" )
public class Struct implements Serializable
{
    private static final long serialVersionUID = 2L;
 
    private int idStruct;
    private String someData;
    private Struct parent;
    private Set<Struct> children;
 
    @Id
    @GeneratedValue
    @Column( name="id_struct", scale=0 )
    public int getIdStruct()
    {
        return idStruct;
    }
    public void setIdStruct(int idStruct)
    {
        this.idStruct = idStruct;
    }
 
    @Column( name="some_data", nullable = false, length = 10 )
    public String getSomeData()
    {
        return someData;
    }
    public void setSomeData(String someData)
    {
        this.someData = someData;
    }
 
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn( name = "id_struct_parent", nullable = true )
    public Struct getParent()
    {
        return this.parent;
    }
    public void setParent( Struct parent )
    {
        this.parent = parent;
    }
 
    @OneToMany( fetch = FetchType.LAZY, mappedBy="parent")
    public Set<Struct> getChildren()
    {
        return this.children;
    }
    public void setChildren( Set<Struct> children )
    {
        this.children = children;
    }
 
}

By the way, you can find a detailed documentation of the one-to-many relationship in hibernate here:

http://www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example-annotation/