2009-12-14 8 views
30

Ich versuche Spring + Hibernate + JPA für die Arbeit mit zwei Datenbanken (MySQL und MSSQL) zu konfigurieren.Mehrere Datenbanken mit Spring + Hibernate + JPA

Meine Datenquelle-context.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd" 
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 
xmlns:util="http://www.springframework.org/schema/util"> 

<!-- 
Data Source config 
    --> 
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
    destroy-method="close" p:driverClassName="${local.jdbc.driver}" p:url="${local.jdbc.url}" 
    p:username="${local.jdbc.username}" p:password="${local.jdbc.password}"> 
</bean> 

<bean id="dataSourceRemote" class="org.apache.commons.dbcp.BasicDataSource" 
    destroy-method="close" p:driverClassName="${remote.jdbc.driver}" 
    p:url="${remote.jdbc.url}" p:username="${remote.jdbc.username}" 
    p:password="${remote.jdbc.password}" /> 

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" 
    p:entity-manager-factory-ref="entityManagerFactory" /> 

<!-- 
    JPA config 
    --> 
<tx:annotation-driven transaction-manager="transactionManager" /> 

<bean id="persistenceUnitManager" 
    class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager"> 
     <property name="persistenceXmlLocations"> 
    <list value-type="java.lang.String"> 
    <value>classpath*:config/persistence.local.xml</value> 
    <value>classpath*:config/persistence.remote.xml</value> 
    </list> 
    </property> 

    <property name="dataSources"> 
    <map> 
    <entry key="localDataSource" value-ref="dataSource" /> 
    <entry key="remoteDataSource" value-ref="dataSourceRemote" /> 
    </map> 
    </property> 
    <property name="defaultDataSource" ref="dataSource" /> 
</bean> 

<bean id="entityManagerFactory" 
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
    <property name="jpaVendorAdapter"> 
    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" 
    p:showSql="true" p:generateDdl="true"> 
    </bean> 
    </property> 
    <property name="persistenceUnitManager" ref="persistenceUnitManager" /> 
<property name="persistenceUnitName" value="localjpa"/> 
</bean> 

<bean 
    class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> 

</beans> 

Jede persistence.xml eine Einheit enthält, wie folgt aus:

<persistence-unit name="remote" transaction-type="RESOURCE_LOCAL"> 
    <properties> 
    <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" /> 
    <property name="hibernate.dialect" value="${remote.hibernate.dialect}" /> 
    <property name="hibernate.hbm2ddl.auto" value="${remote.hibernate.hbm2ddl.auto}" /> 
    </properties> 
</persistence-unit> 

PersistenceUnitManager Ursache folgender Ausnahme:

nicht Verweis auflösen kann zu Bean 'PersistenceUnitManager' bei der Einstellung Bean p Eigenschaft 'persistenceUnitManager'; nested Ausnahme ist org.springframework.beans.factory.BeanCreationException: Fehler beim Erstellen Bean mit Namen 'persistenceUnitManager' definiert in Klassenpfad Ressource [config/datasource-context.xml]: Initialization of bean fehlgeschlagen; verschachtelte Ausnahme ist org.springframework.beans.TypeMismatchException: Fehler beim Eigenschaftswert von Typ [java.util.ArrayList] auf die gewünschte Typ [java.lang.String] für Eigenschaft 'persistenceXmlLocation' zu konvertieren; verschachtelte Ausnahme ist java.lang.IllegalArgumentException: nicht Wert vom Typ umwandeln kann [java.util.ArrayList] auf die gewünschte Art [java.lang.String] für Immobilien ‚persistenceXmlLocation‘: keine passenden Editoren oder Wandlungsstrategie Wenn nur ein persistence.xml ohne Liste links

gefunden, arbeitet jeder feinen aber ich brauche 2 Einheiten ...

ich versuche auch alternative Lösung für die Arbeit mit zwei Datenbanken in Spring + Hibernate Kontext zu finden also würde ich mich über jeden freuen Lösung.

New Fehler nach persistenceXmlLocations an sich ändernde:

Keine einzige Standard Persistenzeinheit definiert in {Classpath: config/persistence.local.xml, Classpath: config/persistence.remote.xml}

Update:

Ich füge persistenceUnitName, es funktioniert, aber nur mit einer Einheit, noch Hilfe brauchen.

Update:

I Konfigurationsdateien geändert: Datenquelle-context.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 
     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd" 
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:util="http://www.springframework.org/schema/util"> 

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
     destroy-method="close" p:driverClassName="${local.jdbc.driver}" p:url="${local.jdbc.url}" 
     p:username="${local.jdbc.username}" p:password="${local.jdbc.password}"> 
    </bean> 

    <bean id="dataSourceRemote" class="org.apache.commons.dbcp.BasicDataSource" 
     destroy-method="close" p:driverClassName="${remote.jdbc.driver}" 
     p:url="${remote.jdbc.url}" p:username="${remote.jdbc.username}" 
     p:password="${remote.jdbc.password}"> 
    </bean> 

    <bean 
     class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"> 
     <property name="defaultPersistenceUnitName" value="pu1" /> 
    </bean> 

    <bean id="persistenceUnitManager" 
     class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager"> 
     <property name="persistenceXmlLocation" value="${persistence.xml.location}" /> 
     <property name="defaultDataSource" ref="dataSource" /> <!-- problem --> 
     <property name="dataSources"> 
      <map> 
       <entry key="local" value-ref="dataSource" /> 
       <entry key="remote" value-ref="dataSourceRemote" /> 
      </map> 
     </property> 
    </bean> 

    <bean id="entityManagerFactory" 
     class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
     <property name="jpaVendorAdapter"> 
      <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" 
       p:showSql="true" p:generateDdl="true"> 
      </bean> 
     </property> 
     <property name="persistenceUnitManager" ref="persistenceUnitManager" /> 
     <property name="persistenceUnitName" value="pu1" /> 
     <property name="dataSource" ref="dataSource" /> 
    </bean> 

    <bean id="entityManagerFactoryRemote" 
     class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
     <property name="jpaVendorAdapter"> 
      <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" 
       p:showSql="true" p:generateDdl="true"> 
      </bean> 
     </property> 
     <property name="persistenceUnitManager" ref="persistenceUnitManager" /> 
     <property name="persistenceUnitName" value="pu2" /> 
     <property name="dataSource" ref="dataSourceRemote" /> 
    </bean> 

    <tx:annotation-driven /> 

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" 
     p:entity-manager-factory-ref="entityManagerFactory" /> 


    <bean id="transactionManagerRemote" class="org.springframework.orm.jpa.JpaTransactionManager" 
     p:entity-manager-factory-ref="entityManagerFactoryRemote" /> 

</beans> 

Ausdauer.xml

<?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="pu1" transaction-type="RESOURCE_LOCAL"> 
     <properties> 
      <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" /> 
      <property name="hibernate.dialect" value="${local.hibernate.dialect}" /> 
      <property name="hibernate.hbm2ddl.auto" value="${local.hibernate.hbm2ddl.auto}" />       
     </properties> 
    </persistence-unit> 

    <persistence-unit name="pu2" transaction-type="RESOURCE_LOCAL"> 
     <properties> 
      <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" /> 
      <property name="hibernate.dialect" value="${remote.hibernate.dialect}" /> 
      <property name="hibernate.hbm2ddl.auto" value="${remote.hibernate.hbm2ddl.auto}" /> 
     </properties> 
    </persistence-unit> 

</persistence> 

Jetzt ist es zwei EntityManagerFactory baut, aber beide sind für Microsoft SQL Server

[main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [ 
    name: pu1 
    ...] 
[main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: Microsoft SQL Server 

[main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [ 
    name: pu2 
    ...] 
[main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: Microsoft SQL Server (but must MySQL) 

Ich schlage vor, dass nur Datasource, dataSourceRemote (keine Substitution) nicht funktionierte. Das ist mein letztes Problem.

Antwort

15

Sie müssen persistenceXmlLocations Eigenschaft (beachten Sie die Mehrzahl) statt persistenceXmlLocation verwenden. Es ist ein String-Array, so dass es automatisch umgewandelt aus der Liste sein wird:

<bean id="persistenceUnitManager" 
     class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager"> 
    <property name="persistenceXmlLocations"><list> 
    <value>classpath*:config/persistence.local.xml</value> 
    <value>classpath*:config/persistence.remote.xml</value> 
    </list></property> 
    ... 

aktualisiert (basierend auf edit)

Ihre entityManagerFactory nicht festgelegt, persistenceUnitName Eigenschaft. Sie müssen dies explizit tun, weil Sie mehr als eine Persistenzeinheit definieren, und entityManagerFactory muss wissen, welche zu verwenden ist.

+0

:) Danke, Sie haben Recht, aber jetzt habe ich neue Fehler – ziftech

+0

falls diese noch einen Bezug zu diesem, Sie vielleicht kann deine Frage aktualisieren und ich werde einen Blick darauf werfen. Wenn es nicht direkt verwandt ist, ist es wahrscheinlich besser, eine neue Frage zu stellen. – ChssPly76

+1

ok, also wenn ich persistenceUnitName explizit setze, funktioniert es, aber nur mit einer Einheit. Wie kann ich Einheiten in der Anwendung wechseln? – ziftech

6

Wenn Sie dieses Tutorial folgen, http://www.javacodegeeks.com/2010/05/jboss-42x-spring-3-jpa-hibernate.html können Sie folgende Änderungen vornehmen zwei verschiedene Datenbanken zugreifen:

  1. persistence.xml, eine zweite pesristence-Einheit für Ihre zweite Datenbank definieren.
  2. spring.xml, definieren Sie eine zweite EntityManagerFactory-Bean unter einem anderen Namen, sagen wir "entityManagerFactoryDB2" und konfigurieren Sie es für die Verwendung der persistenten Einheit für die zweite Datenbank.
  3. für jede DAO Sie die zweite Datenbank zugreifen möchten, gehören die folgenden:

    @Autowired 
    private EntityManagerFactory entityManagerFactoryDB2; 
    
    @PostConstruct 
    public void init() { 
        super.setEntityManagerFactory(entityManagerFactoryDB2); 
    } 
    

Das ist alles!

Verwenden Sie die DAOs wie gewohnt im Frühling!

8

Justin, Nummer 3 kann so in einem Standardverfahren durchgeführt werden:

  1. In Ihrem Frühling Kontext:

    <context:annotation-config /> 
    
  2. In Ihrem Frühlings-Managed DAOs (beachten Sie die unitname Eigenschaft):

    @PersistenceContext(unitName = "pu1"`) protected EntityManager entityManager; 
    

Auf diese Weise würde ein richtig intantiierter EntityManager, der der Persistenzeinheit namens "pu1" entspricht, in die entsprechenden DAOs injiziert.

+0

Ich glaube nicht, dass Spring das unitName-Attribut vor Version 3 unterstützt, zu Ihrer Information. – Lyle

1

ich das Problem gelöst auf diese Weise (Wie mehrere Datenbank mit Feder und Hibernate verbinden), ich hoffe, es wird dazu beitragen, :) HINWEIS:Ich habe den entsprechenden Code hinzugefügt, bitte machen Sie den Dao mit Hilfe von Impl ich in den unten genannten Code verwendet.

**web.xml** 

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
    id="WebApp_ID" version="3.0"> 
    <display-name>MultipleDatabaseConnectivityInSpring</display-name> 
    <welcome-file-list> 
     <welcome-file>index.jsp</welcome-file> 
    </welcome-file-list> 
    <servlet> 
     <servlet-name>dispatcher</servlet-name> 
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
     <load-on-startup>1</load-on-startup> 
    </servlet> 
    <listener> 
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
    </listener> 
    <context-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value> 
      /WEB-INF/dispatcher-servlet.xml 
     </param-value> 
    </context-param> 
    <servlet-mapping> 
     <servlet-name>dispatcher</servlet-name> 
     <url-pattern>*.htm</url-pattern> 
    </servlet-mapping> 
    <session-config> 
     <session-timeout>30</session-timeout> 
    </session-config> 
</web-app> 


**persistence.xml** 


<?xml version="1.0" encoding="UTF-8"?> 
<persistence version="1.0" 
    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"> 
    <persistence-unit name="localPersistenceUnitOne" 
     transaction-type="RESOURCE_LOCAL"> 
     <provider>org.hibernate.ejb.HibernatePersistence</provider> 
     <class>in.india.entities.CustomerDetails</class> 
     <exclude-unlisted-classes /> 
     <properties> 
      <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" /> 
      <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" /> 
      <property name="hibernate.jdbc.batch_size" value="0" /> 
      <property name="hibernate.show_sql" value="false" /> 
      <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/shankar?sslmode=require" /> 
      <property name="hibernate.connection.username" value="username" /> 
      <property name="hibernate.connection.password" value="password" /> 
      <property name="hibernate.hbm2ddl.auto" value="update" /> 
     </properties> 
    </persistence-unit> 
    <persistence-unit name="localPersistenceUnitTwo" 
     transaction-type="RESOURCE_LOCAL"> 
     <provider>org.hibernate.ejb.HibernatePersistence</provider> 
     <class>in.india.entities.CompanyDetails</class> 
     <exclude-unlisted-classes /> 
     <properties> 
      <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" /> 
      <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" /> 
      <property name="hibernate.jdbc.batch_size" value="0" /> 
      <property name="hibernate.show_sql" value="false" /> 
      <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/shankarTwo?sslmode=require" /> 
      <property name="hibernate.connection.username" value="username" /> 
      <property name="hibernate.connection.password" value="password" /> 
      <property name="hibernate.hbm2ddl.auto" value="update" /> 
     </properties> 
    </persistence-unit> 
</persistence> 


**dispatcher-servlet** 


<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:task="http://www.springframework.org/schema/task" xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util" 
    default-autowire="byName" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
     http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc 
     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 
    <!-- Configure messageSource --> 

    <mvc:annotation-driven /> 
    <context:component-scan base-package="in.india.*" /> 
    <bean id="messageResource" 
     class="org.springframework.context.support.ResourceBundleMessageSource" 
     autowire="byName"> 
     <property name="basename" value="messageResource"></property> 
    </bean> 

    <bean 
     class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <property name="prefix"> 
      <value>/WEB-INF/jsp/</value> 
     </property> 
     <property name="suffix"> 
      <value>.jsp</value> 
     </property> 
    </bean> 



    <bean id="entityManagerFactoryOne" 
     class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" 
     autowire="constructor"> 
     <property name="persistenceUnitName" value="localPersistenceUnitOne" /> 
    </bean> 

    <bean id="messageSource" 
     class="org.springframework.context.support.ResourceBundleMessageSource" 
     autowire="byName"> 
     <property name="basename" value="messageResource" /> 
    </bean> 

    <bean id="entityManagerFactoryTwo" 
     class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" 
     autowire="constructor"> 
     <property name="persistenceUnitName" value="localPersistenceUnitTwo" /> 
    </bean> 

    <bean id="manager1" class="org.springframework.orm.jpa.JpaTransactionManager"> 
     <property name="entityManagerFactory" ref="entityManagerFactoryOne" /> 
    </bean> 

    <bean id="manager2" class="org.springframework.orm.jpa.JpaTransactionManager"> 
     <property name="entityManagerFactory" ref="entityManagerFactoryTwo" /> 
    </bean> 

    <tx:annotation-driven transaction-manager="manager1" /> 
    <tx:annotation-driven transaction-manager="manager2" /> 

    <!-- declare dependies here --> 

    <bean class="in.india.service.dao.impl.CustomerServiceImpl" /> 
    <bean class="in.india.service.dao.impl.CompanyServiceImpl" /> 

    <!-- Configure MVC annotations --> 
    <bean 
     class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> 
    <bean 
     class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 
    <bean 
     class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> 
</beans> 



**java class to persist into one database** 


package in.india.service.dao.impl; 

import in.india.entities.CompanyDetails; 
import in.india.service.CompanyService; 

import javax.persistence.EntityManager; 
import javax.persistence.PersistenceContext; 

import org.springframework.transaction.annotation.Transactional; 

public class CompanyServiceImpl implements CompanyService { 

    @PersistenceContext(unitName = "entityManagerFactoryTwo") 
    EntityManager entityManager; 

    @Transactional("manager2") 
    @Override 
    public boolean companyService(CompanyDetails companyDetails) { 

     boolean flag = false; 
     try 
     { 
      entityManager.persist(companyDetails); 
      flag = true; 
     } 
     catch (Exception e) 
     { 
      flag = false; 
     } 

     return flag; 
    } 

} 


**java class to persist in another database** 

package in.india.service.dao.impl; 

import javax.persistence.EntityManager; 
import javax.persistence.PersistenceContext; 

import org.springframework.transaction.annotation.Transactional; 

import in.india.entities.CustomerDetails; 
import in.india.service.CustomerService; 

public class CustomerServiceImpl implements CustomerService { 

    @PersistenceContext(unitName = "localPersistenceUnitOne") 
    EntityManager entityManager; 

    @Override 
    @Transactional(value = "manager1") 
    public boolean customerService(CustomerDetails companyData) { 

     boolean flag = false; 
     entityManager.persist(companyData); 
     return flag; 
    } 
} 


**customer.jsp** 

<%@page language="java" contentType="text/html; charset=ISO-8859-1" 
    pageEncoding="ISO-8859-1"%> 
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title>Insert title here</title> 
</head> 
<body> 
    <center> 
     <h1>SpringWithMultipleDatabase's</h1> 
    </center> 
    <form:form method="GET" action="addCustomer.htm" modelAttribute="customerBean" > 
     <table> 
      <tr> 
       <td><form:label path="firstName">First Name</form:label></td> 
       <td><form:input path="firstName" /></td> 
      </tr> 
      <tr> 
       <td><form:label path="lastName">Last Name</form:label></td> 
       <td><form:input path="lastName" /></td> 
      </tr> 
      <tr> 
       <td><form:label path="emailId">Email Id</form:label></td> 
       <td><form:input path="emailId" /></td> 
      </tr> 
      <tr> 
       <td><form:label path="profession">Profession</form:label></td> 
       <td><form:input path="profession" /></td> 
      </tr> 
      <tr> 
       <td><form:label path="address">Address</form:label></td> 
       <td><form:input path="address" /></td> 
      </tr> 
      <tr> 
       <td><form:label path="age">Age</form:label></td> 
       <td><form:input path="age" /></td> 
      </tr> 
      <tr> 
       <td><input type="submit" value="Submit"/></td> 
      </tr> 
     </table> 
    </form:form> 
</body> 
</html> 


**company.jsp** 


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title>ScheduleJobs</title> 
</head> 
<body> 
<center><h1>SpringWithMultipleDatabase's</h1></center> 
<form:form method="GET" action="addCompany.htm" modelAttribute="companyBean" > 
<table> 
    <tr> 
     <td><form:label path="companyName">Company Name</form:label></td> 
     <td><form:input path="companyName" /></td> 
    </tr> 
    <tr> 
     <td><form:label path="companyStrength">Company Strength</form:label></td> 
     <td><form:input path="companyStrength" /></td> 
    </tr> 
    <tr> 
     <td><form:label path="companyLocation">Company Location</form:label></td> 
     <td><form:input path="companyLocation" /></td> 
    </tr> 
    <tr> 
     <td> 
      <input type="submit" value="Submit"/> 
     </td> 
    </tr> 
</table> 
</form:form> 
</body> 
</html> 

**index.jsp** 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
    pageEncoding="ISO-8859-1"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title>Home</title> 
</head> 
<body> 
<center><h1>Multiple Database Connectivity In Spring sdfsdsd</h1></center> 

<a href='customerRequest.htm'>Click here to go on Customer page</a> 
<br> 
<a href='companyRequest.htm'>Click here to go on Company page</a> 
</body> 
</html> 

**success.jsp** 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
    pageEncoding="ISO-8859-1"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title>ScheduleJobs</title> 
</head> 
<body> 
<center><h1>SpringWithMultipleDatabase</h1></center> 
    <b>Successfully Saved</b> 
</body> 
</html> 

**CompanyController** 

package in.india.controller; 

import in.india.bean.CompanyBean; 
import in.india.entities.CompanyDetails; 
import in.india.service.CompanyService; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.ui.ModelMap; 
import org.springframework.web.bind.annotation.ModelAttribute; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.servlet.ModelAndView; 

@Controller 
public class CompanyController { 

    @Autowired 
    CompanyService companyService; 

    @RequestMapping(value = "/companyRequest.htm", method = RequestMethod.GET) 
    public ModelAndView addStudent(ModelMap model) { 
     CompanyBean companyBean = new CompanyBean(); 
     model.addAttribute(companyBean); 
     return new ModelAndView("company"); 
    } 

    @RequestMapping(value = "/addCompany.htm", method = RequestMethod.GET) 
    public ModelAndView companyController(@ModelAttribute("companyBean") CompanyBean companyBean, Model model) { 
     CompanyDetails companyDetails = new CompanyDetails(); 
     companyDetails.setCompanyLocation(companyBean.getCompanyLocation()); 
     companyDetails.setCompanyName(companyBean.getCompanyName()); 
     companyDetails.setCompanyStrength(companyBean.getCompanyStrength()); 
     companyService.companyService(companyDetails); 
     return new ModelAndView("success"); 

    } 
} 

**CustomerController** 


package in.india.controller; 

import in.india.bean.CustomerBean; 
import in.india.entities.CustomerDetails; 
import in.india.service.CustomerService; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.ui.ModelMap; 
import org.springframework.web.bind.annotation.ModelAttribute; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.servlet.ModelAndView; 

@Controller 
public class CustomerController { 

    @Autowired 
    CustomerService customerService; 

    @RequestMapping(value = "/customerRequest.htm", method = RequestMethod.GET) 
    public ModelAndView addStudent(ModelMap model) { 
     CustomerBean customerBean = new CustomerBean(); 
     model.addAttribute(customerBean); 
     return new ModelAndView("customer"); 
    } 

    @RequestMapping(value = "/addCustomer.htm", method = RequestMethod.GET) 
    public ModelAndView customerController(@ModelAttribute("customerBean") CustomerBean customer, Model model) { 
     CustomerDetails customerDetails = new CustomerDetails(); 
     customerDetails.setAddress(customer.getAddress()); 
     customerDetails.setAge(customer.getAge()); 
     customerDetails.setEmailId(customer.getEmailId()); 
     customerDetails.setFirstName(customer.getFirstName()); 
     customerDetails.setLastName(customer.getLastName()); 
     customerDetails.setProfession(customer.getProfession()); 
     customerService.customerService(customerDetails); 
     return new ModelAndView("success"); 

    } 
} 


**CompanyDetails Entity** 


package in.india.entities; 

import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
import javax.persistence.SequenceGenerator; 
import javax.persistence.Table; 

@Entity 
@Table(name = "company_details") 
public class CompanyDetails { 

    @Id 
    @SequenceGenerator(name = "company_details_seq", sequenceName = "company_details_seq", initialValue = 1, allocationSize = 1) 
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "company_details_seq") 
    @Column(name = "company_details_id") 
    private Long companyDetailsId; 
    @Column(name = "company_name") 
    private String companyName; 
    @Column(name = "company_strength") 
    private Long companyStrength; 
    @Column(name = "company_location") 
    private String companyLocation; 

    public Long getCompanyDetailsId() { 
     return companyDetailsId; 
    } 

    public void setCompanyDetailsId(Long companyDetailsId) { 
     this.companyDetailsId = companyDetailsId; 
    } 

    public String getCompanyName() { 
     return companyName; 
    } 

    public void setCompanyName(String companyName) { 
     this.companyName = companyName; 
    } 

    public Long getCompanyStrength() { 
     return companyStrength; 
    } 

    public void setCompanyStrength(Long companyStrength) { 
     this.companyStrength = companyStrength; 
    } 

    public String getCompanyLocation() { 
     return companyLocation; 
    } 

    public void setCompanyLocation(String companyLocation) { 
     this.companyLocation = companyLocation; 
    } 
} 


**CustomerDetails Entity** 

package in.india.entities; 

import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
import javax.persistence.SequenceGenerator; 
import javax.persistence.Table; 

@Entity 
@Table(name = "customer_details") 
public class CustomerDetails { 

    @Id 
    @SequenceGenerator(name = "customer_details_seq", sequenceName = "customer_details_seq", initialValue = 1, allocationSize = 1) 
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customer_details_seq") 
    @Column(name = "customer_details_id") 
    private Long customerDetailsId; 
    @Column(name = "first_name ") 
    private String firstName; 
    @Column(name = "last_name ") 
    private String lastName; 
    @Column(name = "email_id") 
    private String emailId; 
    @Column(name = "profession") 
    private String profession; 
    @Column(name = "address") 
    private String address; 
    @Column(name = "age") 
    private int age; 
    public Long getCustomerDetailsId() { 
     return customerDetailsId; 
    } 

    public void setCustomerDetailsId(Long customerDetailsId) { 
     this.customerDetailsId = customerDetailsId; 
    } 

    public String getFirstName() { 
     return firstName; 
    } 

    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 

    public String getLastName() { 
     return lastName; 
    } 

    public void setLastName(String lastName) { 
     this.lastName = lastName; 
    } 

    public String getEmailId() { 
     return emailId; 
    } 

    public void setEmailId(String emailId) { 
     this.emailId = emailId; 
    } 

    public String getProfession() { 
     return profession; 
    } 

    public void setProfession(String profession) { 
     this.profession = profession; 
    } 

    public String getAddress() { 
     return address; 
    } 

    public void setAddress(String address) { 
     this.address = address; 
    } 

    public int getAge() { 
     return age; 
    } 

    public void setAge(int age) { 
     this.age = age; 
    } 
} 
0
  1. mehrere EntityManagerFactory schaffen, um jede Persistenzeinheit entspricht.
  2. angeben unitname Eigenschaft für @PersistenceContext

Schalter unter den entityManagerFactories diejenigen injiziert werden