Hibernate is much faster when executing a native request

The next query should return about 800 objects. The problem is that hibernate actually executes 800 requests to get all of them. It seems that it performs one request for identifiers, and then performs one request for each object to obtain specific data about the object. It takes more than 60 seconds to return this request.

List<AUser> result = em.createQuery("FROM AUser where company=:companyId")
.setParameter("companyId",company.getId())
.getResultList();

Native query is much faster.

List<AUser> result = em.createNativeQuery("select a.* FROM AUser a where a.company=:companyId")
.setParameter("companyId",company.getId())
.getResultList();

The above request takes less than one second to return.

Why is the difference?

+3
source share
2 answers

, AUser ( HappyEngineer ).

:

, :

@ManyToOne(fetch = FetchType.LAZY)
private Company company;

join fetch:

select user
  from AUser user left join fetch user.company
 where user.company.id = :companyId

. " Hibernate.

+6

n + 1 select Hibernate. . , Lazy Loading, Fetch Mode, Fetch Join ..

http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html n + 1

...

+1

Source: https://habr.com/ru/post/1724671/


All Articles