title: JPA/Hibernate 50% slower than using simple JDBC
body: <p>First I would like to say that I'm far of being an expert with JPA and Hibernate. But I came across something that I'm completely stuck as I don't understand how things are working underneath and don't know how to debug it.</p>
  
  <p>I have a webapp (Spring + JPA2.0). I have an algorithm that calculate a score for a user with data coming from the PostrgeSQL database. To benchmark the speed of the algorithm I have ran the calculation on 1 user.</p>
  
  <p>It took 72 seconds. (i found this time a bit strange because i know it shouldn't take THAT long)</p>
  
  <p>So what I did is replaced the database call (entityManger.createQuery(...)) by a Simple JDBC connection (<code>conn = DriverManager.getConnection(url, props);)</code> and I pull the data from the DB without using JPA.</p>
  
  <p>it took 35 seconds to calculate the score for the same user...</p>
  
  <p>Is it normal that using JPA makes the calculation <strong>50%</strong> slower?? I mean I would have think that yes the time would have been "a bit" more than simply using jdbc but <strong>50%</strong> ??</p>
  
  <p>Is there any configuration that i don't know about that would explain this difference?</p>
  
  <p>Here is the pseudo code of the algo. calculateScore is call within a loop 2000 times:</p>
  
  <pre><code>public double calculateScore(userId, placeId) {
  
  //This returns in average 5 columns
  List&lt;Object[]&gt; datas = entityManager.createNativeQuery("SELECT info1, info2, info3 WHERE user_id=.. and place_id=...").getResultList();
  ..
  ..
  for (Object[] result : datas) {
   info1 = result[0] // Integer
   info2 = result[1] // Integer
   info3 = result[2] // Double
  
   if (info3 == null) {
       info3 = calculateMissing(..)
   }
  
   .. calculation ..
  
   return result
  }
  
  private double calculateMissing(..) {
  
      //this query returns maximum 20 rows 
      List&lt;Double&gt; data =  entityManager.createNativeQuery("SELECT info FROM..."). getResultList;
  
  
      //So here we could have UP TO 20 call to the db
      while(some cond) {
         data2 =  entityManager.createNativeQuery("SELECT * FROM...).getOne()
         if (data2 ..)
           cond = false
        ..
        }
  
      ... calculation ..
  
     return result;
  }
  </code></pre>
  
  <p>So here are my "three" little select to the DB. </p>
  
  <p><strong>EDIT 1</strong></p>
  
  <p>I have tried narrowing where "exactly" the problem was. I have replaced one by one the call from jdbc to JPA. and it appears that the while loop was the one making the 50% (well almost) time loss. Doing dis was a really bad idea from the start, but I didn't know that JPA was not gonna like this AT ALL.</p>
  
  <p>I have replaced the while loop with a smarter SQL query. And now the algorithm runs in <strong>15 seconds instead of 70 seconds!</strong></p>
  
  <p><strong>And in 12 seconds instead of 35 for the JDB version.</strong></p>