title: Spring + Hibernate + JPA + multiple databases
body: <p>I have a Spring + Hibernate + JPA app. The user, when logging in, can choose from a list of DB's to connect to (these are the requirements). All the DB's have the same schema, so the same entities and DAO's will be used.</p>
  
  <p>Right now I have one EntityManager (been working with one database for the moment) that is injected in the DAO like this:</p>
  
  <pre><code>@PersistenceContext
  private EntityManager entityManager;
  </code></pre>
  
  <p>Is there any way to have the DAO receive the entityManager automatically (managed by Spring) based on a parameter/property received from the service layer ? (The web layer sends a kind of context, and the name/code/id of the chosen database will be in there).</p>
  
  <p>Or do I have to manage this myself (creating all the entityManagers, putting them in a map, telling the DAO which one of them to use for each call) ?</p>
  
  <p>I did some research before asking this, but the results were inconclusive - most of the questions dealt with a model spread over 2 or more DB's and transactions spanning multiple DB's, but this is not the case for me. </p>
  
  <p>In my case, once the user is connected, it's just as if he connected to an application that only has one entity manager, the one for the database he selected. There's no switching between DB's mid-session or any other such stuff.</p>
  
  <p>Thank you.</p>