0

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?

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.