Spring Hibernate Multiple Database Connection

Spring Hibernate Multiple Database Connection

Integration of Spring with Hibernate and configuration with single database is common where you will make only one database connection. But making connection to multiple database is little tricky where you will have to tweak you context. In this demo I will show you how to make multiple database connection. I will use Sybase ASM 15.7 of-course you could configure to make connection to any database. To understand better I will create sample project and how to how to connect two database by the way I will be connecting Sybase database only but different schema.

  • Create maven project name: SpringHibernateMultipleDatabase and below is details structure of the project:

Spring Hibernate Multiple Database Connection

Important: If you don’t want to read all documentation and looking for solution immediately then please have a look these two hibernate context file where configuration has been done for two database and how we are creating session factory beans:

  • hibernate-context.xml

  • hibernate-context-anotherdb.xml:

Now let’s go over to the full project file and its structure:

  • First create table using below script in Sybase database

  • Insert some dummy data for test:

Note: If you are using any data configure table and data accordingly. 

  • pom.xml:

  • application.properties:

  • hibernate.properties

  • hibernate.queries.xml:

  • spring-context.xml:

  • EquitySwapInterestRateModel.java:

  • EquitySwapTestModel.java:

  • LocalDateHibernateUserType.java:

  • LocalDateTimeHibernateUserType.java:

  • GenericDao.java:

  • GenericDaoHandler.java:

  • InterestRateDao.java:

  • InterestRateDaoHandler.java:

  • log4j2.xml:

  • SpringHibernateMultipleTestApp.java: This is our main test class and I will be making call to both the database through DAO:

  • That’s it. To test this application one all your configuration is done then right click SpringHibernateMultipleTestApp.java Run As –> Java Application you should see output based on your database and table configuration. As I did tested it on Sysbase below was my output on console:

  • For more information please visit Spring documentation here

download Download Project: SpringHibernateMultipleDatabase

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *