Each company has two properties, they are company name and estimated annual earnings. There are two types of companies: 1- Main company, 2 - Subsidiary company. The company can belong only to one company but can have a few child companies.
2 Answers
With @Entity
you define a class to become an entity. with @Column
you define which attributes map to which table columns. After that you need to define your relationships, in this case a self reference to the same table (parent company to child company), you can define it like this:
@ManyToOne
private Company parentCompany;
@OneToMany(mappedBy = "parentCompany", fetch = FetchType.EAGER)
private Set<Company> childCompanies;

- 4,316
- 3
- 43
- 40
-
There are many of them, so it should be named `childCompanies`. Naming is crucial. Why use FetchType EAGER instead of using the sane default, especially for a recursive association like this. Loading any cmpany will force the loading of the whole company tree. – JB Nizet Jul 09 '17 at 09:55
-
thanks i edited the name, but for the fetch type i usually use eager for better performance :) in my answer it is a hint that you can control how to fetch relationships. – Mr.Q Jul 09 '17 at 10:02
-
Using EAGER for toMany associations is the best way to ruin the performance – JB Nizet Jul 09 '17 at 10:04
-
I guess not. what if you want to do some repetitive operation on childCompanies :) – Mr.Q Jul 09 '17 at 10:10
Just to set you in the right direction, you need to look at association mapping, Hibernate provides field/method annotation for defining associations - of particular note in your case;
@Entity
@OneToMany
@ManyToOne
I'd recommend taking some time to familiarize yourself with the Hibernate Documentation on the subject; it's fundamental to using hibernate. Google for some starer tutorials on the subject to get you started - there are so many out there (here for example). I'm sure you can get more help if you run into specific problems when you get started.

- 587
- 4
- 14