ovnia
ovnia

Reputation: 2500

Simple object hierarchy with Hibernate

How to make hierarhical mapping Hibernate?

For example: Category

id parent_id name
1  0         Root
2  1         Sub-root 1
3  1         Sub-root 2
4  2         Sub-(sub-root 1)

Is it possible to make lazy mapping for such Category object?

Upvotes: 0

Views: 684

Answers (2)

Alan Hay
Alan Hay

Reputation: 23246

It is not exactly clear what you are asking.

However it would appear you are talking about a self-referencing relationship rather than Inheritance so you can then map as below. The default fetch strategy should be same as for any other @OneToMany i.e. LAZY.

@Entity
public class Category{

    @Id
    private Long id;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Category parent;

    @OneToMany(mappedBy = "parent")
    private Set<Category> subCategories;
}

Upvotes: 2

Prasad Kharkar
Prasad Kharkar

Reputation: 13566

I believe you want to ask about inheritance of entities. I recommend using JPA inheritance strategies. There are 3 available.

  1. Single Table: Uses only one database table. columns need to be nullable and hence wastes database space
  2. Joined Strategy: Uses multiple table which can be joined for insertion and retrieval of entity data. Saves database space but performance becomes an issue when inheritance hierarchy becomes wide and deep
  3. Table per concrete class: Uses separate database tables which are not joined.

Different strategies have different advantages and disadvantages. You can choose according to your need.

Upvotes: 1

Related Questions