0
votes

We have the requirement to insert records into two data sources using JPA.

What is the correct approach to this problem?

How can we declare different persistence units with different data sources and manage two entity managers and inject with default persistence context for default unit name without mentioning the unit name in the generic dao for first datasource and overriding the context with the unit name in a separate dao for other tables in second datasource.

The spring documentation is very limited and has no example.

Examples would be of great help.

2
Are they the same record/table on each data source? - Jeff Watkins
no they are different records .. but one table has id being used in other one . they are legacy tables ..so no room to modify much there - naveen_stack_over_flow
Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 2 - naveen_stack_over_flow
This just feels like something you should be doing with triggers or replication - Jeff Watkins
we are not allowed to use triggers. - naveen_stack_over_flow

2 Answers

0
votes

Use

<bean class="..." primary="true" />

or @Primary if you are using annotations.

This will indicated that one instance is the "default" instance of a type that you define multiple different instances of (like your EntityManagerFactory).

0
votes

If you follow this tutorial, http://javacodegeeks.blogspot.com/2010/05/jboss-42x-spring-3-jpa-hibernate.html you can make the following changes to access two different databases:

persistence.xml, define a second pesristence-unit for your second database. spring.xml, define a second entityManagerFactory bean under a different name, lets say "entityManagerFactoryDB2" and configure it to use the persistent unit for the second database. for every DAO you want to access the second database include the following :

@Autowired
private EntityManagerFactory entityManagerFactoryDB2;


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

Thats all!

On spring service classes, use the DAOs as usual!