简体   繁体   中英

How to use Spring to manage connection to multiple databases

I have read other topics but didn't find a good and clear answer

What I'm trying to is to develop a web app which is able to:

1) Log/track user events in a seperate UI database which we connect via hibernate with the same database schema (maybe save connectionString to the different oracle databases)

2) At runtime when you log in you can choose an environment to connect to one of the three different oracle databases that have the same schema (but not the same data)

3) provide the correct DataSource with username and password (where to get this sensitive data? I would not keep this stored somewhere in the application)

I'm fairly new to the Spring framework. I found this link which could be a first lead.

Any suggestions?

Also using Spring 3.1 or 3.2, JDBC to query to my oracle database and hibernate mapping to my UI database. This sounds quite confusing so I have a picture:

infrastructure

Just create different DAOs each with a separate persistence-unit attached to them. In your persistence.xml you can have multiple persistence-unit's each connecting to a different database.

Example:

public class Dao1{
@PersistenceContext(unitName="Database1")
protected EntityManager entityManager;

public class Dao2{
@PersistenceContext(unitName="Database2")
protected EntityManager entityManager;


<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">
    <persistence-unit name="Database1">     
        <exclude-unlisted-classes />                    
        <properties>
        </properties>
    </persistence-unit>

    <persistence-unit name="Database2">     
        <exclude-unlisted-classes />                    
        <properties>
        </properties>
    </persistence-unit>
</persistence>

The link you have mentioned in your post says following:

1) create different data sources pointing to different schema.

2) extends AbstractRoutingDataSource and create your own data source, override determineCurrentLookupKey method which will provide value of key. in your case it will return whatever user choose from UI. also in the bean definition of your custom data source pass all the data source as map with key as option available at UI.

3) Now assign this data source into your session factory bean.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM