Win a copy of Transfer Learning for Natural Language Processing (MEAP) this week in the Artificial Intelligence and Machine Learning forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Paul Clapham
  • Devaka Cooray
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Knute Snortum
  • Liutauras Vilda
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Piet Souris
Bartenders:
  • salvin francis
  • Carey Brown
  • Frits Walraven

Injection Dependency in Spring

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • 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: 89
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • 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.
 
Ranch Hand
Posts: 1871
12
  • Likes 1
  • Mark post as helpful
  • send pies
  • 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:

 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    Bookmark Topic Watch Topic
  • New Topic