Reputation: 191
I am having trouble with many-to-one mapping using hibernate. I have two tables, Table A and Table B. I mapped Many-to-One Relationship between these tables. Both tables can be use together as well as separately.
The representation of tables in terms of classes in Java like:
class A{
private B b;
private Integer val1;
private Integer val2;
private Integer val3;
}
class B{
private Integer val1;
private Integer val2;
private Integer val3;
}
The problem is whenever I try to retrieve/fetch records from table A, hibernate also fetch records from Table B all the time which I do not want. It causing performance issues. Is their any way to deal with this situation?
Please guide me with an appropriate answer.
Upvotes: 1
Views: 2563
Reputation: 2137
Your requirement fits into Lazy Initialization
. For achieving it, you can add either annotation or while retrieving data you can use hibernate session's get
method.
In your case you can write like :
Session session = SessionFactory.getCurrentSession();
A aObject= (A) session.get(A.class, A_ID);
As stated in this https://community.jboss.org/wiki/AShortPrimerOnFetchingStrategies?_sscc=t link :
Hibernate3 loads a single entity instance if you retrieve it by identifier through get() or load(). All collections mapped for this entity, and all associated entities, be it through to-many or to-one associations, are not loaded.
Upvotes: 0
Reputation: 691765
@ManyToOne(lazy = true)
private B b;
Is all you need. Read the hibernate documentation for more details.
Upvotes: 2