• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

Injection Dependency in Spring

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm writing an app that talks to one database, obtains credentials for other databases, and connects to the others. It does this using a DataSource and EntityManagerFactory constructed at runtime.

If I want to use Spring Data Repositories, I think I'd need to Autowire them, and therefore they must be Spring Beans.

How can I use Spring Data if I don't have a constructed DataSource until after I run a query against the first database?
 
Ranch Hand
Posts: 93
1
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
All your datasources will be created when the app first loads, via component scan.  You just won't be able to 'open' the secondary datasource until you get the credentials from the first datasource.
 
Bartender
Posts: 2265
13
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, Mason,
Would you mind to post your example code so that we can see what you are working on?
In Spring Data JPA, you can simply create something like this:

Suppose you have a table called Person and the table primary key is an integer.

In your service layer, you can autowire the PersonRepository like this:


In your resources folder, create a data.sql file and put something like this:


In your pom.xml, include the following dependencies. The second one indicate that you want to your embedded H2 database.

If you want to use MySQL database, you may want to include this instead of h2database:

And also specify the url of the MySQL database in application.properties in resources folder:

 
reply
    Bookmark Topic Watch Topic
  • New Topic