hibernate: list of child ids retrieval for parent
Technology: Hibernate 3.0
Suppose i have Entity class Company
@Entity
@Table(name="tbl_companies")
public class Company
{
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
@Column(name="name")
String companyName;
@OneToMany(mappedBy = "company")
List<Employees> empList;
@OneToMany(mappedBy = "company")
List<Projects> projectList;
@OneToMany(mappedBy = "company")
List<Department> deptList;
@OneToMany(mappedBy = "company")
List<Branch> branchList;
}
In Entity Company which is mapped to database by hibernate annotation contains list of of other entities related to it. Since objects of these Entities like Branch, Project, Employee itself are heavy objects, it will make Company object very heavy and contains almost whole of db data. One way to avoid this is to use lazy loading. One other approach can be to use List branchIdList, List projectId开发者_JAVA百科List that is list of ids for objects. My question which approach is standard practice and better to use in such situation. Better to use includes factors like performance in term of memory mainly, flexibility for programmer(first one is one flexible for programmer and second one uses less memory). Another question is if i use second approach what will be change in annotation. I doubt if hibernate supports list of ids or support full fledged objects only.
Thanks
One other approach can be to use List branchIdList, List projectIdList that is list of ids for objects.
Please think very carefully before doing this. The whole point of using an ORM is so that rows in DB that are linked to each other via foreign keys can be represented as objects linked via regular java references and collections. By using the scheme you outlined, you will loose most of the advantages of using Hibernate.
The recommended approach is to using lazy loading.
Better to use includes factors like performance in term of memory mainly, flexibility for programmer(first one is one flexible for programmer and second one uses less memory).
IMHO, the memory you gain, if any, is not worth the programmer pain it causes.
I think, you have to first see your use cases for retrieving Company object. Means for example, there are too many scenarios where Employees is retrieved with Company object. There are less scenarios where Projects is retrieved with Company object. So, following these, you can remove Projects list from Company object and make it many-to-one from Project object (retrieve it manually). So, analyse all your scenarios and make some relations many-to-one. Make other list lazy.
精彩评论