Question about Hibernate POJO class design
I am learning hibernate and have 开发者_如何学JAVAa question regarding the design of my POJO class i have a class destination with few properties like
private Set<AirTransport> airTransport;
private Set<RoadTransport> roadTransport;
private Set<TrainTransport> trainTransport;
since these are refrence to some other entity classes,My question is when i will fetch my destination class i don't want these refrence to get loaded in to the memory so that can fetch them later on when user click on any one of the link like (airtransport).how this can be achieve in best way. I am ne to Hibernate so please correct me where ever i am wrong.
Thnaks in advance
This is called "lazy loading". By default all collections in hibernate (and JPA) are loaded lazily - that is, they are not loaded until they are accessed. So by default your object won't fetch all the data.
But lazy loading has its complications. If you try to access a collection when the hibernate session has been closed, an exception is thrown. And as it seems you will be needing the collections after the user makes some action (clicks a button).
For that case you have two options:
when the user clicks the button, you load the entity again, and initialize the desired collection. Either by
Hibernate.initialize(..)
or by iterating it in the view. Note that sessions are normally closed before the view is rendered, so you may needOpenSessionInViewFilter
don't use collections at all. They have limited behaviour anyway. Use HQL or the criteria API to fetch the results. This allows you to have paging, and you are not thinking of lazy problems
This is called Lazy Fetch in ORM world. Read the tutorial here. You might also want to read about related pattern: Open Session in View
精彩评论