Camel file uri using property - properties

I'm trying to use property file for routing from folder :
My property file has some property :
from.file = D:/Develop/resources
and I want to use it in camel context xml as file routing,
I tried:
<camel:route id="Main-Route">
<camel:from uri="file:${from.file}" />
<camel:to uri="seda:fooQueue" />
</camel:route>
But camel throws me exception :
Dynamic expressions with ${ } placeholders is not allowed. Use the fileName option to set the dynamic expression.
How can I do this ?

In Camel, you use {{property}} to inject properties in your routes.
Please read more here http://camel.apache.org/properties.html.
Your example would change to:
<camel:route id="Main-Route">
<camel:from uri="file:{{from.file}}" />
<camel:to uri="seda:fooQueue" />
</camel:route>
You also need to tell Camel where it can find your properties file. From the link above:
Spring XML offers two variations to configure. You can define a spring bean as a PropertiesComponent which resembles the way done in Java DSL. Or you can use the tag.
<bean id="properties" class="org.apache.camel.component.properties.PropertiesComponent">
<property name="location" value="classpath:com/mycompany/myprop.properties"/>
</bean>
Using the tag makes the configuration a bit more fresh such as:
<camelContext ...>
<propertyPlaceholder id="properties" location="com/mycompany/myprop.properties"/>
</camelContext>

In file component of apache camel,the starting directory should not contain dynamic expressions. If you want to provide dynamic starting directory also,you can set the whole path into CamelFileName header of file component from properties file with fileComponent defined as <to uri="file://">

the problem with this is that for reading place holder as :
${some-property} for some bean for example :
<bean id="bean" class="">
<property name="field Constructor" value="${some.property}" />
</bean>
I get error.
Solved it by defining also PropertyPlaceholderConfigurer:
<bean id="proprty" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>file:/D:/Proj/resources/myprop.properties
</value>
</bean>
<bean id="beanId" class="com.viewlinks.eim.properties.MyBean">
<property name="fieldConstructor" value="${some.property}" />
</bean>
<camel:camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
<propertyPlaceholder id="properties" location="file:/D:/Proj/resources/myprop.properties"/>
<camel:route id="Main-Route">
<camel:from uri="file:{{from.file}}" />
<camel:to uri="file:{{to.file}}" />
</camel:route>
</camel:camelContext>

Related

Configuring Consumer Cancellation in RabbitMQ

We are using an 2-Node active-active RabbitMQ cluster with mirrored queue. With the mirroring policy being :
"policies":[{"vhost":"/","name":"ha-all","pattern":"","apply->to":"all","definition":{"ha-mode":"all","ha-sync-mode":"automatic"},"priority":0}]
Versions : RabbitMQ 3.5.4, Erlang 17.4 , spring-amqp/spring-rabbit :1.4.5.RELEASE
Now,we are trying to achieve consumer cancellation,as mentioned in Highly Available Queues.
However,since we have not used channel,we can't use {{basicConsumer}} method as given in the above link.
How do I set,"x-cancel-on-ha-failover" to true in the configuration,itself?
With the beans xml being thus :
<rabbit:connection-factory id="connectionFactory"
addresses="localhost:5672"
username="guest"
password="guest"
channel-cache-size="5" />
<!-- CREATE THE JsonMessageConverter BEAN -->
<bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.JsonMessageConverter" />
<!-- Spring AMQP Template -->
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" retry-template="retryTemplate" message-converter="jsonMessageConverter" />
<!-- in case connection is broken then Retry based on the below policy -->
<bean id="retryTemplate" class="org.springframework.retry.support.RetryTemplate">
<property name="backOffPolicy">
<bean class="org.springframework.retry.backoff.ExponentialBackOffPolicy">
<property name="initialInterval" value="500" />
<property name="multiplier" value="2" />
<property name="maxInterval" value="30000" />
</bean>
</property>
</bean>
<rabbit:queue name="testQueue" durable="true">
<rabbit:queue-arguments>
<entry key="x-max-priority">
<value type="java.lang.Integer">10</value>
</entry>
</rabbit:queue-arguments>
</rabbit:queue>
<bean id="messsageConsumer" class="consumer.RabbitConsumer">
</bean>
<rabbit:listener-container
connection-factory="connectionFactory" concurrency="5" max-concurrency="5" message-converter="jsonMessageConverter">
<rabbit:listener queues="testQueue" ref="messsageConsumer" />
</rabbit:listener-container>
The <rabbit:listener-container> actually populates a SimpleMessageListenerContainer bean on background. And the last one supports public void setConsumerArguments(Map<String, Object> args) on the matter.
So, to fix your requirements you just need to build the raw SimpleMessageListenerContainer <bean> for your messsageConsumer.
Meanwhile you are fixing that for your application, I'd ask you for the JIRA regarding adding <consumer-arguments> component. And we may be able to address it with the current GA deadline.

WSO2 xml property xpath to child element

I have following code:
<property name="resultOM" scope="default" type="OM">
<test><test1>testing111</test1></test>
</property>
<log level="full">
<property name="ROOT" expression="$ctx:resultOM" />
<property name="resultOM.test" expression="$ctx:resultOM//test1" />
</log>
Then I would expect to see in logs values
ROOT = testing111
resultOM.test = testing111
and although ROOT value is fine, the value of resultOM.test is empty.
What should be the correct xpath to retrieve the child value?
Version of used WSO2ESB is 4.5.1.
A default namespace (http://ws.apache.org/ns/synapse) is defined when you create an OM type property. So you need to perform xpath expressions with namespaces. Try this;
<log level="full">
<property name="ROOT" expression="$ctx:resultOM"/>
<property name="resultOM.test" xmlns:ns="http://ws.apache.org/ns/synapse" expression="$ctx:resultOM//ns:test1"/>
</log>
Read [1] for more details.
[1] http://isharapremadasa.blogspot.com/2014/08/wso2-esb-property-mediator-performing.html

Display Hibernate SQL To Console (Spring)

I'm working with spring 3, hibernate 4. I'm trying to follow this tutorial http://www.mkyong.com/hibernate/hibernate-display-generated-sql-to-console-show_sql-format_sql-and-use_sql_comments/, but my hibernate configuration is different:
<?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:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
<!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
username root and blank password. Change below if it's not the case -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/project"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
<property name="validationQuery" value="SELECT 1"/>
<property name="show_sql" value="true" />
<property name="format_sql" value="true" />
<property name="use_sql_comments" value="true" />
</bean>
</beans>
And the properties show_sql, format_sql and use_sql_comments are not working this way. I get this exception:
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'show_sql' of bean class [org.apache.commons.dbcp.BasicDataSource]: Bean property 'show_sql' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
Is there anyway to achieve the tutorial with the definition of the bean??
show_sql not a property of org.apache.commons.dbcp.BasicDataSource . You have to define it in session factory configuration.
like this
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="data" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
The simplest approach probably is to set following logger to DEBUG:
org.hibernate.SQL
If you use log4j, find / create a log4j.properties file on your classpath root and add
log4j.logger.org.hibernate.SQL=DEBUG
See here for more info about log4j properties: http://logging.apache.org/log4j/1.2/manual.html
As I'm using JEE 8 and JBoss EAP, I managed to got the SQL after adding this line:
-Dorg.jboss.as.logging.per-deployment=false
on the end of "VM arguments" (Server tab -> JBoss Properties -> Open lauch configuration).

error when running red5 application on windows

I made very sample application for red5
I set WEB-INF(red5-web.properties, red5-web.xml, web.xml)
when I runnig the red.bat I view in the debug this error code :
[INFO] [Launcher:/test] org.springframework.beans.factory.xml.XmlBeanDefi
nitionReader - Loading XML bean definitions from ServletContext resource [/WEB-I
NF/red5-web.xml]
Exception in thread "Launcher:/test" org.springframework.beans.factory.xm
l.XmlBeanDefinitionStoreException: Line 25 in XML document from ServletContext r
esource [/WEB-INF/red5-web.xml] is invalid; nested exception is org.xml.sax.SAXP
arseException; lineNumber: 25; columnNumber: 68; cvc-id.2: There are multiple oc
currences of ID value 'web.handler'
and my client can't connect to server :(
from your description its impossible to say exactly what you've done.
You might better start to use for example the existing demo application that ship with every release.
Sebastian
<?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:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd">
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/red5-web.properties" />
</bean>
<bean id="web.context" class="org.red5.server.Context"
autowire="byType" />
<bean id="web.scope" class="org.red5.server.WebScope"
init-method="register">
<property name="server" ref="red5.server" />
<property name="parent" ref="global.scope" />
<property name="context" ref="web.context" />
<property name="handler" ref="web.handler" />
<property name="contextPath" value="${webapp.contextPath}" />
<property name="virtualHosts" value="${webapp.virtualHosts}" />
</bean>
<bean id="web.handler" class="com.myapp.Application" />
</beans>
change the web.handler bean in your red5-web.xml file
<bean id="web.handler" class="com.myapp.Application"
singleton="true" autowire="byName" />
Check the other bean names also. The error you posted says same ID used for two or more beans.

Eclipselink & Spring Data

I am trying to implement a solution using a combination of eclipselink (2.4.0) and spring-data-jpa (1.1.0.RELEASE). However, every time I deploy the solution (Tomcat 7), I get the following exception:
Caused by: java.lang.IllegalArgumentException: No [ManagedType] was found for
the key class [com.acme.domain.entities.User] in the Metamodel - please
verify that the [Managed] class was referenced in persistence.xml using a
specific <class>com.acme.domain.entities.User</class> property or a global
<exclude-unlisted-classes>false</exclude-unlisted-classes> element.
It appears to occur when the repository autowiring takes place (code examples below):
Service class
#Component
public class UserDataService {
#Autowired
private UserRepository userRepository;
...
}
Entity class
package com.acme.domain.entities;
...
#Entity
#Table(name = "users")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private Integer id;
...
}
persistence.xml
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.acme.domain.entities.User</class>
...
</persistence-unit>
Can this be due to some conflict between spring and eclipselink?
UPDATE:
Stacktrace...
[#|2012-07-31 16:25:02,317|ERROR|pool-2-thread-40|org.springframework.web.context.ContextLoader|Context initialization failed|#]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDataService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.acme.data.repositories.UserRepository com.acme.data.services.UserDataService.userRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: No [ManagedType] was found for the key class [com.acme.domain.entities.User] in the Metamodel - please verify that the [Managed] class was referenced in persistence.xml using a specific <class>com.acme.domain.entities.User</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:897)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:873)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:958)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1599)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.acme.data.repositories.UserRepository com.acme.data.services.UserDataService.userRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: No [ManagedType] was found for the key class [com.acme.domain.entities.User] in the Metamodel - please verify that the [Managed] class was referenced in persistence.xml using a specific <class>com.acme.domain.entities.User</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:512)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 27 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: No [ManagedType] was found for the key class [com.acme.domain.entities.User] in the Metamodel - please verify that the [Managed] class was referenced in persistence.xml using a specific <class>com.acme.domain.entities.User</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:149)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:102)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1442)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:305)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:876)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:818)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:735)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:484)
... 29 more
Caused by: java.lang.IllegalArgumentException: No [ManagedType] was found for the key class [com.acme.domain.entities.User] in the Metamodel - please verify that the [Managed] class was referenced in persistence.xml using a specific <class>com.acme.domain.entities.User</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.entityEmbeddableManagedTypeNotFound(MetamodelImpl.java:174)
at org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:489)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:58)
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:65)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:149)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:87)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:70)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:137)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:125)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:41)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142)
... 37 more
I was able to solve my issue but it was another setup as the one above, i just add a few things i stumbled across until i was able to solve it in my SE-Environment:
Bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=338837 affects EclipseLink Version 2.2.0 and below versions. Mostly happening in Local-Environment (RESOURCE_LOCAL). A EclipseLink version-Upgrade or the following workaround may help:
<exclude-unlisted-classes>false</exclude-unlisted-classes>
Having multiple persistence.xml files in classpath (e.g. especially in 3th party JARs) that all define the same persistence-unit-name (above "default" may be very common). Try renaming your persistence-unit-name in this case as a first step
In case of renaming the persistence-unit-name worked but changing it back to the old value reproduces the problem there is either above mentioned 3th party JAR or old JARs of your own project beeing included to your build (e.g. refactoring/ renaming on project level or similar changed the structure so for example a maven build could still take old build artifacts from the repository)
Finaly when it comes to my setup (Spring-Standalone Application, no persistence.xml but tons of Spring-configurations because a custom company Framework is used) it showed that i just forgot to add the the entity-package of the custom framework-core when i wanted to run one of their service-implementations (Spring-Bean implementation) in my local project rather than having their service-implementation from a JAR-dependency. So make sure that you have all of the required entity packages listed for your EntityManagerFactory:
<bean id="customEntityManagerFactory" parent="abstractEntityManagerFactory">
<property name="dataSource" ref="dataSource"/>
<!-- Packages of EntityClasses -->
<property name="packagesToScan">
<list merge="true">
<value>ch.company.div1.foo.bar.model</value>
<value>ch.company.div1.foo.barnicle.model</value>
<value>ch.company.div2.we.help.model</value>
</list>
</property>
<property name="jpaProperties">
<props merge="true">
<prop key="eclipselink.target-database">org.eclipse.persistence.platform.database.SQLServerPlatform
</prop>
<prop key="javax.persistence.transactionType">RESOURCE_LOCAL</prop>
</props>
</property>
</bean>
In my case i forgot to add the model packagege with the used entitys of another division (that writes the custom framework core) of our company.
Good luck, that error's a beast :/
Not sure if you are having the same problem I had: trying to create 2 different entity factories... The exception is the same, so maybe this will help. Essentially this exception was happening when it was instantiating an Entity on the wrong EntityManagerFactory.
My project was running fine with a single database connection but when I added a second one EclipseLink was confused on where to instantiate my entities. After a few debug my conclusion was to remove the property "packagesToScan" from my root-context.xml and replace it with a "persistenceXmlLocation". In that XML, I listed every class I needed to be scanned and excluded everything else with "<exclude-unlisted-classes>"
Here is my full XML configuration that is currently working:
root-context.xml
<bean id="dataSource1" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://server1.example.com:5432/db1" />
<property name="username" value="username" />
<property name="password" value="password" />
<property name="defaultAutoCommit" value="false" />
<property name="initialSize" value="5" />
<property name="maxIdle" value="5" />
<property name="validationQuery" value="SELECT 1" />
<property name="timeBetweenEvictionRunsMillis" value="600000" />
<property name="poolPreparedStatements" value="true" />
<property name="maxOpenPreparedStatements" value="10" />
</bean>
<bean id="dataSource2" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://server2.example.com:5432/db2" />
<property name="username" value="user" />
<property name="password" value="password" />
<property name="defaultAutoCommit" value="false" />
<property name="initialSize" value="5" />
<property name="maxIdle" value="5" />
<property name="validationQuery" value="SELECT 1" />
<property name="timeBetweenEvictionRunsMillis" value="600000" />
<property name="poolPreparedStatements" value="true" />
<property name="maxOpenPreparedStatements" value="10" />
</bean>
<bean id="emf1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource1" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence1.xml" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="showSql" value="false" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false" />
<entry key="eclipselink.logging.level" value="WARNING" />
<entry key="eclipselink.logging.timestamp" value="false" />
<entry key="eclipselink.logging.session" value="false" />
<entry key="eclipselink.logging.thread" value="false" />
</map>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean id="emf2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource2" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence2.xml" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="showSql" value="false" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false" />
<entry key="eclipselink.logging.level" value="WARNING" />
<entry key="eclipselink.logging.timestamp" value="false" />
<entry key="eclipselink.logging.session" value="false" />
<entry key="eclipselink.logging.thread" value="false" />
</map>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean name="transaction1" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="emf1" />
<bean name="transaction2" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="emf2" />
<jpa:repositories base-package="org.myproject.repository1" transaction-manager-ref="transaction1" entity-manager-factory-ref="emf1" />
<jpa:repositories base-package="org.myproject.repository2" transaction-manager-ref="transaction2" entity-manager-factory-ref="emf2" />
<tx:annotation-driven />
persistence1.xml
<persistence-unit name="persistence1" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.myproject.repository1.Repo1</class>
<class>org.myproject.repository1.Repo2</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
persistence2.xml
<persistence-unit name="persistence2" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.myproject.repository2.Repo1</class>
<class>org.myproject.repository2.Repo2</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
So, this works for me...
Apparently specifying each "persistence.xml" location prevents classes that are meant for another EntityManagerFactory to be instantiated on the first "emf". In fact, this looks like a bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=338837. All I could figure out from my debugging is that without the "persistenceXmlLocation" ALL classes that are found with "packageScan" were instantiated on the first created "emf", the second "emf" was completely ignored.
Hope this helps. Good luck!
Add the package (com.acme.domain.entities) with entities to packagesToScan.
Set the PersistenceUnitName, instead of the persistenceXmlLocation
No persistence.xml needed.
factory.setPersistenceUnitName("dummy1");
factory.setPersistenceUnitName("dummy2");