2

For example let us say that there is a table called "Class" and a lot of "Students" belong to a class. If we want to get the first name of the all the students, with Hibernate since we fetch Student objects, the last name, the age and other data (which is not lazy loaded) will also be fetched.

But with an sql query, we can fetch only the first name.

So does this mean that using Hibernate results in unwanted data being fetched? If so, would it not make a large impact on the performance of a system?

Can't Tell
  • 10,924
  • 9
  • 54
  • 84

2 Answers2

2

If you want to get the first name of students in a class in hibernate you can try the below HQL,

select s.firstName from Student s where s.divisionId = 4

This will give you the list of first names of students only. So, last name, age etc will not be loaded. Hence for the scenario in your questions you can get good performance using hibernate.

Now when you need the List<Students> of division 4 use the below query,

select s from Student s where s.divisionId = 4

Imagine writing this query in SQL and converting each and every column to its corresponding java properties etc.. All theses hibernate does it for you in the above. So, you can tune hibernate according to your requirement.

When it comes to the performance of hibernate, it is little slower than the traditional JDBC but much more convenient and effective than JDBC. Basically the the benefits you receive from the hibernate overrules the smaller drawbacks.

You should learn about the performance pitfalls in hibernate like Lazy loading and should try to avoid those.

Community
  • 1
  • 1
ManuPK
  • 10,995
  • 9
  • 54
  • 75
1

Yes, Hibernate would fetch all the fields which are not lazy loaded. Its impact on performance depends upon the use cases of your application. If you frequently need partial (i.e. only one or two columns) data from a table which contains many columns (say > 10), then it would definitely increase memory usage, CPU cycles needed and the bandwidth consumption to transfer the data (if the database server is on different machine than the application server). To overcome this problem you can use NamedQuery. In the named query you can just select the required columns.

vikas
  • 1,466
  • 1
  • 13
  • 22