0

I have different database for different projects but all those database has same table names .I am creating a analytics service for all these projects, i don't want to create separate analytics service for all these projects since the database sql queries are the same.I want to have one service for all these projects with different controllers with base url remaining the same. For e.g baserl/foo/getuserDetails , baseurl/bar/getuserDetails.

How can I interact with multiple database based on the request recieved.For e.g if request comes with url /foo/getuserDetails , services should fetch data from user table of foo database, if request comes with url /bar/getuserDetails , services should fetch data from user table of bar database.

application.properties file

spring.datasource.url=jdbc:sqlserver://..;databaseName=foo
spring.datasource.username=user1
spring.datasource.password=Password1
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect

spring.datasource.url=jdbc:sqlserver://..;databaseName=bar
spring.datasource.username=user2
spring.datasource.password=Password2
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect


@Service("analyticsService")
public class AnalyticsServiceImpl implements AnalyticsService {
    

    @PersistenceContext
    private EntityManager entityManager;

I want to have this one single method called when the request is received either with baseurl/foo or baseurl/bar since the Query(GET_USER_DETAILS) is the same. All I want is when request is received with url baseurl/foo , usertable of foo database is called, if request is received with url baseurl/bar , usertable of bar database is called, similarly if request is received with url baseurl/test , usertable of test database is called

public int countReqRaisedWithinDateRange(Date fromDate,Date toDate) {
        Query query = entityManager.createNativeQuery(GET_USER_DETAILS);
        query.setParameter("fromDate", fromDate);
        query.setParameter("toDate",toDate);
        int count = ((Number) query.getSingleResult()).intValue();
        return count;
    }
Gitesh
  • 346
  • 2
  • 4
  • 14
  • Please take a look at this https://stackoverflow.com/questions/30337582/spring-boot-configure-and-use-two-datasources – Pramod Jan 03 '22 at 07:27
  • I don't see a way to use entity manager, i want to inject entity manager.This link only shows the creation of datasource – Gitesh Jan 03 '22 at 07:36

0 Answers0