Reputation: 75
I am trying to understand the best solution for the following use case. Any inputs would be really helpful.
Consider the following scenario: A,B,C,D are four tables, with One to many mapping between them.
A --> B --> C --> D
A (One) --> B (Many) and so on..
My use case is, I need to get the data from table A based on a column value in D which is not a primary key.
As per my understanding (Still new to Hibernate, so please correct me if i am wrong :)), there are 2 approach
Approach 1: Using the get() method First get the primary key value using the hibernate Query and then call the get method
Query query = sessionFactory.getCurrentSession().createQuery("from D where ...");
Int id = query.list().get(0).getId();
this.sessionFactory.getCurrentSession().get(id);
Approach 2: Use hibernate query and joins Create a string by joining all the 4 tables and pass to the create query method.
Query query = sessionFactory.getCurrentSession().createQuery(sql);
I want to know:
- Is there a way to call get method by passing non primary key column value
- apart from these approach is there any other approach?
- which is better approach
Thanks in advance.
Upvotes: 0
Views: 810
Reputation: 691765
Using a dedicated query returning the wanted data directly will of course be more efficient that executing a query to find D, and then getting C from D, B from C and finally A from B. Especially if the associations are lazy.
Efficiency is not the only thing that matters, though. But since you need to write a query to get D anyway, I would write the query to get the wanted information instead.
Just a note on your first strategy:
int id = query.list().get(0).getId();
D d = (D) this.sessionFactory.getCurrentSession().get(id);
The second line is completely useless. It will return the entity that was already found by the query. All you need is
D d = (D) query.list().get(0);
or better, since the query should return a single entity
D d = (D) query.uniqueResult();
Also, what you pass to createQuery() is not SQL. It's HQL. Those are different languages.
Upvotes: 1