title: Spring boot + JPA - SharedEntityManagerCreator opens sessions at startup
body: <p>Given the following setup :</p>
  
  <ul>
  <li>Spring boot 1.4</li>
  <li>Hibernate 5 / Multi-Tenancy is ON / MultiTenancyStrategy is DataBase.</li>
  <li><code>spring.jpa.open-in-view=true</code>, <code>spring.jpa.properties.hibernate.hbm2ddl.auto=none</code>, <code>spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false</code>, <code>spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect</code></li>
  </ul>
  
  <p>When enabling tracing, I have noticed that hibernate opens <code>n</code> sessions at startup.</p>
  
  <p>The <code>n</code> number is <strong>oddly</strong> equal to the number of methods annotated by <code>@org.springframework.transaction.annotation.Transactional(readOnly=true)</code>.</p>
  
  <p>I also noticed that the component responsible of opening those sessions is the <code>org.springframework.orm.jpa.SharedEntityManagerCreator</code>, and precisely the following part of code :</p>
  
  <pre class="lang-java prettyprint-override"><code>@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      //...
  
      boolean isNewEm = false;
      if (target == null) {
          logger.debug("Creating new EntityManager for shared EntityManager invocation");
          target = (!CollectionUtils.isEmpty(this.properties) ?
                  this.targetFactory.createEntityManager(this.properties) :
                  this.targetFactory.createEntityManager());
          isNewEm = true;
      }
  
      //...
  }
  </code></pre>
  
  <p>And here is a <a href="https://i.stack.imgur.com/BmESy.png" rel="nofollow noreferrer">link</a> to a screenshot showing the method being proxied.</p>
  
  <p><strong>That being said, my question is :</strong></p>
  
  <p>Is there any explanation for this behavior because I'm expecting that no session will be opened until the application has completely started or a data manipulation operation <em>(loading schema)</em> is required during startup (which is not my case)...</p>