title: Obtaining handle to EntityManager in Spring Boot
body: <p>Is there any way to get a handle to the EntityManager for a given entity object? I'm using spring boot 1.2.3 with JPA starter and i'm further explicitly configuring multiple data sources with <code>@configuration</code></p>
  
  <p>I've checked <a href="https://stackoverflow.com/questions/26425067/resolvedspring-boot-access-to-entitymanager">[resolved]SPRING BOOT access to entityManager</a> and it doesn't seem to answer the question. </p>
  
  <p>Thanks.</p>
  
  <p><strong>EDIT: I added description of how my data sources are defined:</strong></p>
  
  <pre><code>@Component
  @Configuration
  public class DataSources {
      @Bean
      @Primary
      @ConfigurationProperties(prefix="first.datasource")
      public DataSource getPrimaryDataSource() {
          return DataSourceBuilder.create().build();
      }
  
      @Bean
      @ConfigurationProperties(prefix="second.datasource")
      public DataSource getSecondDataSource() {
          return DataSourceBuilder.create().build();
      }
  
      @Bean
      @ConfigurationProperties(prefix="third.final.datasource")
      public DataSource getThirdFinalDataSource() {
          return DataSourceBuilder.create().build();
      }
  }
  </code></pre>
  
  <p>In my application.yml I have the following sections</p>
  
  <pre><code>first.datasource:
    name: 'first_datasource',
    #other attributes...
  second.datasource:
    name: 'second_datasource',
    #other attributes...
  third.final.datasource:
    name: 'first_datasource',
    #other attributes...
  </code></pre>
  
  <p>So far I've tried both of @Stephane's suggestions but I get <code>NoSuchBeanDefinitionException</code> </p>
  
  <p>Let's say my entity is called <code>Customer</code> then I tried </p>
  
  <pre><code>@Service
  public class FooService {
  
      private final EntityManager entityManager;
  
      @Autowired
      public FooService(@Qualifier("customerEntityManager") EntityManager entityManager) {
          ...
      }
  
  }
  </code></pre>
  
  <p>But I also tried </p>
  
  <pre><code>@PersistenceContext(unitName = "customer") // also tried "customers" and "first_datasource"
  private EntityManager entityManager;
  </code></pre>
  
  <p>with no luck.</p>