SpringBoot - Multimodule projet & datasources - Unable to scan #Entity.class - spring-boot

I have some trouble to configure my multimodule projet with multiple datasources. So, I need your help.
I have allready try :
Springboot multimodule project
SpringBoot ComponentScan issue with multi-module project
SpringBoot scanBasePackages not working in multi module project
And https://mhdevelopment.wordpress.com/2014/09/16/how-to-configure-spring-boot-with-jpa-and-multiple-projects/
But nothing work, i have the same issue.
So, that m'y multi-module classpath:
BusinessModule, that include repositories and Entities:
base package : com.mycompany.business.
In that module, i have an external dependency where we can found #Entity class ( package : com.mycompany.model)
RestModule, that are used to use BusinessModule.
base package : com.mycompany.rest
Business configuration
Configuration for datasources
First data source:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory",
basePackages = {
"com.mycompany.business.repository", "com.mycompany.model" })
#PropertySource(value =
"file:${CPROCESS_INSTALL}/server/custom_config/datasources.properties")
public class BusinessDbConfig {
#Primary
#Bean(name = "dataSource")
#ConfigurationProperties(prefix = "business.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("dataSource") DataSource dataSource) {
return builder.dataSource(dataSource)
.packages("com.mycompany.business.model", "com.mycompany.model")
.persistenceUnit("business").build();
}
#Primary
#Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
Second data source:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "barEntityManagerFactory", transactionManagerRef = "barTransactionManager", basePackages = {
"com.mycompany.bonita.repository" })
#PropertySource(value = "file:${CPROCESS_INSTALL}/server/custom_config/datasources.properties")
public class BonitaDbConfig {
#Bean(name = "barDataSource")
#ConfigurationProperties(prefix = "bonita.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "barEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean barEntityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("barDataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("com.mycompany.bonita.model")
.persistenceUnit("bar").build();
}
#Bean(name = "barTransactionManager")
public PlatformTransactionManager barTransactionManager(
#Qualifier("barEntityManagerFactory") EntityManagerFactory barEntityManagerFactory) {
return new JpaTransactionManager(barEntityManagerFactory);
}
}
Repository configuration
#RepositoryRestResource
public interface CDocumentRepository extends JpaRepository<CDocument, Long> {
#Query("select dp from CDocument d where d.persistenceid = ?1")
public CDocument findByPersistenceId(Long persistenceId);
}
Entity
#javax.persistence.Entity(name = "CDocument")
#Table(name = "CDOCUMENT")
public class CDocument{ ... }
Rest module configuration
App configuration
#SpringBootApplication(scanBasePackages= {"com.mycompany"})
#EnableJpaRepositories("com.mycompany")
#EntityScan("com.mycompany")
#Import({ BonitaDbConfig.class, BusinessDbConfig.class })
public class RestApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(RestApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(RestApplication.class, args);
}
}
My controller
#RestController
public class CreateSpaceController {
private CDocushareConnectRepository cDocushareConnectRepository;
private CDocumentRepository cDocumentRepository;
private DocumentRepository documentRepository;
private CustomtableRepository customTableRepository;
private CFieldsMappingRepository cFieldsMappingRepository;
public CreateSpaceController(CDocumentRepository cDocumentRepository) {
super();
this.cDocumentRepository = cDocumentRepository;
}
...
}
When i try to start test or app, i have this error:
java.lang.IllegalArgumentException: Not a managed type: class com.mycompany.model.CDocument
I don't know why... Any help ?

Related

Spring Boot - Configure two datasources

I want to configure two data sources for my application. My application starts up fine and seems both of my repositories give expected response (from two Databases) when I write query directly above the JPA repository method as below.
#Repository
public interface DB2Repo extends JpaRepository<DB2Entity, Integer>{
#Query(nativeQuery = true, value = "SELECT * from \"TABLE_1\"")
List<DB2Entity> findAll();
}
But, when I try to directly utilize the available JPA method like below:
#Repository
public interface DB2Repo extends JpaRepository<DB2Entity, Integer>{
}
and if I invoke the JPA method directly in my Controller as below:
#RestController
#CrossOrigin(origins = "*")
#RequestMapping("/db2")
public class DB2Controller {
#Autowired
DB2Repo db2Repo;
#GetMapping("/getList")
public List<DB2Entity> getMovies() {
List<DB2Entity> res = db2Repo.findAll();
return res;
}
}
I get relation does not exist error as below:
Caused by: org.postgresql.util.PSQLException: ERROR: relation "**dbo**.TABLE_1" does not exist
I see that it is automatically looking into dbo schema instead of public schema
Below is my application.properties:
spring.datasource2.url=jdbc:postgresql://localhost:5432/DB1
spring.datasource2.username=//username
spring.datasource2.password=//pwd
spring.datasource.url=jdbc:postgresql://localhost:5432/DB2
spring.datasource.username=//usrname
spring.datasource.password=//pwd
spring.datasource.initialization-mode=always
spring.jpa.properties.hibernate.default_schema = dbo
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.id.new_generator_mappings=false
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
spring.h2.console.enabled=true
spring.jpa.database=default
Following is the DB1 Config class:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories( entityManagerFactoryRef = "DB1EntityManagerFactory", transactionManagerRef = "DB1TransactionManager", basePackages = {
"com.datasource1.repository" } )
#EntityScan("com.datasource1.entity" )
public class Db1Config {
#Primary
#Bean
#ConfigurationProperties("spring.datasource")
public DataSourceProperties SourceProperties() {
return new DataSourceProperties();
}
#Primary
#Bean( name = "DB1Datasource" )
#ConfigurationProperties( prefix = "spring.datasource.configuration" )
public DataSource dataSource()
{
return SourceProperties().initializeDataSourceBuilder()
.type(HikariDataSource.class).build();
}
#Primary
#Bean( name = "DB1EntityManagerFactory" )
public LocalContainerEntityManagerFactoryBean barEntityManagerFactory( EntityManagerFactoryBuilder builder,
#Qualifier( "DB1Datasource" ) DataSource dataSource )
{
return builder.dataSource(dataSource).packages("com.datasource1.entity")
.persistenceUnit("db1").build();
}
#Primary
#Bean( name = "DB1TransactionManager" )
public PlatformTransactionManager barTransactionManager(
#Qualifier( "DB1EntityManagerFactory" ) EntityManagerFactory barEntityManagerFactory )
{
return new JpaTransactionManager(barEntityManagerFactory);
}
}
Following is the DB2Config:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories( entityManagerFactoryRef = "DB2EntityManagerFactory", transactionManagerRef = "DB2TransactionManager", basePackages = {
"com.DB2.repository" } )
#EntityScan( "com.DB2.entity" )
public class Db2Config {
#Bean
#ConfigurationProperties("spring.datasource2")
public DataSourceProperties DB2SourceProperties() {
return new DataSourceProperties();
}
#Bean( name = "DB2Datasource" )
#ConfigurationProperties( prefix = "spring.datasource2.configuration" )
public DataSource dataSource()
{
return DB2SourceProperties().initializeDataSourceBuilder()
.type(HikariDataSource.class).build();
}
#Bean( name = "DB2EntityManagerFactory" )
public LocalContainerEntityManagerFactoryBean barEntityManagerFactory( EntityManagerFactoryBuilder builder,
#Qualifier( "DB2Datasource" ) DataSource dataSource )
{
return builder.dataSource(dataSource).packages("com.DB2.entity")
.persistenceUnit("db2").build();
}
#Bean( name = "DB2TransactionManager" )
public PlatformTransactionManager barTransactionManager(
#Qualifier( "DB2EntityManagerFactory" ) EntityManagerFactory barEntityManagerFactory )
{
return new JpaTransactionManager(barEntityManagerFactory);
}
}
How do I resolve this?
Thank you in advance!

Spring JPA - Single Repository class with multiple JNDIs

I am using Spring JPA Repository to connect to Oracle.
My Repository package is com.demo.infrastructure.repository;
Repository class is StoreRepo.java
#Repository
public interface StoreRepo extends JpaRepository<StoreAttribute, String> {
#Query("select storeAttributeName from StoreAttribute order by storeAttributeName asc")
List<String> fetchAllStoreAttributeNames();
List<StoreAttribute> findAllByOrderByStoreAttributeNameAsc();
}
Problem:
I am using JNDI config to configure data source. Currently it has only one JNDI entry. Now I want to use two user names for the same database, one with admin(read-write) access and the other with user(read-only) access. Both these users will access the same Repository and same entity.
I tried the solutions already available which uses two different repository packages for each data source. But I want the Repository "StoreRepo" to be the same.
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryAdmin",
basePackages = { "com.demo.infrastructure.repository" }
)
public class DataSourceAdminConfig {
#Primary
#Bean(name = "dataSourceAdmin")
public DataSource dataSource() {
return new JndiDataSourceLookup().getDataSource("jdbc/myds_admin");
}
#Primary
#Bean(name = "entityManagerFactoryAdmin")
public LocalContainerEntityManagerFactoryBean
entityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("dataSourceAdmin") DataSource dataSource
) {
return builder.dataSource(dataSource).
packages("com.demo.domain.model.entities").
persistenceUnit("read-write").
build();
}
#Primary
#Bean(name = "transactionManagerAdmin")
public PlatformTransactionManager transactionManager(
#Qualifier("entityManagerFactoryAdmin") EntityManagerFactory
entityManagerFactory
) {
return new JpaTransactionManager(entityManagerFactory);
}
}
I should have two classes like this with different package (Refer basePackages). But I dont want this solution instead want to use single repository package and the same repository class.
Solution that worked for me.
1) Created separate config classes one for admin user and app user each
2) Created seprate entity manager references one for admin user and app user each
3) Instantiated the same Repositoy class (without using #Repository annotation) through java code and using respective entity manager
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryAdmin"
)
public class AdminUserConfig {
#Primary
#Bean(name = "dataSourceAdmin")
public DataSource dataSourceAdmin(#Value("${spring.datasource.admin-user.jndi-name}") String key) {
return new JndiDataSourceLookup().getDataSource(key);
}
#Primary
#Bean(name = "entityManagerFactoryAdmin")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryAdmin(
EntityManagerFactoryBuilder builder,
#Qualifier("dataSourceAdmin") DataSource dataSource
) {
return builder.dataSource(dataSource).
packages("com.demo.domain.model.entities").
persistenceUnit("read-write").
build();
}
#Bean(name = "entityManagerAdmin")
public EntityManager entityManagerAdmin(#Qualifier("entityManagerFactoryAdmin") EntityManagerFactory
entityManagerFactory) {
return SharedEntityManagerCreator.createSharedEntityManager(entityManagerFactory);
}
#Bean(name = "adminRepository")
public StoreRepo readWriteDimStoreRepository(#Qualifier("jpaRepositoryFactoryAdmin")
JpaRepositoryFactory repositoryFactory) {
return repositoryFactory.getRepository(StoreRepo.class);
}
}
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryApp"
)
public class AppUserConfig {
#Primary
#Bean(name = "dataSourceApp")
public DataSource dataSourceApp(#Value("${spring.datasource.App-user.jndi-name}") String key) {
return new JndiDataSourceLookup().getDataSource(key);
}
#Primary
#Bean(name = "entityManagerFactoryApp")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryApp(
EntityManagerFactoryBuilder builder,
#Qualifier("dataSourceApp") DataSource dataSource
) {
return builder.dataSource(dataSource).
packages("com.demo.domain.model.entities").
persistenceUnit("read-only").
build();
}
#Bean(name = "entityManagerAdmin")
public EntityManager entityManagerApp(#Qualifier("entityManagerFactoryApp") EntityManagerFactory
entityManagerFactory) {
return SharedEntityManagerCreator.createSharedEntityManager(entityManagerFactory);
}
#Bean(name = "AppRepository")
public StoreRepo readOnlyStoreRepository(#Qualifier("jpaRepositoryFactoryApp")
JpaRepositoryFactory repositoryFactory) {
return repositoryFactory.getRepository(StoreRepo.class);
}
}
//#Repository
public interface StoreRepo extends JpaRepository<StoreAttribute, String> {
#Query("select storeAttributeName from StoreAttribute order by
storeAttributeName asc")
List<String> fetchAllStoreAttributeNames();
List<StoreAttribute> findAllByOrderByStoreAttributeNameAsc();
}

problem with writing to 2 databases from Spring boot

I was trying this code from github:https://github.com/kodinor/spring-data-many-dbs
It's an example of how to use multiple db's from a Spring-boot application. it worked fine but I added the Spring-boot-starter-web dependency and now I'm getting an error:
>Method requestMappingHandlerMapping in >org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$En>ableWebMvcConfiguration required a single bean, but 2 were found:
> - productDSEmFactory: defined by method 'productDSEmFactory' in class >path resource [com/kodinor/configuration/ProductDBConfiguration.class]
> - userDSEmFactory: defined by method 'userDSEmFactory' in class path >resource [com/kodinor/configuration/UserDBConfiguration.class]
>
>
>Action:
>
>Consider marking one of the beans as #Primary, updating the consumer to >accept multiple beans, or using #Qualifier to identify the bean that should >be consumed<br>
I have two config files:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackageClasses = UserRepository.class, entityManagerFactoryRef = "userDSEmFactory", transactionManagerRef = "userDSTransactionManager")
public class UserDBConfiguration {
#Primary
#Bean
#ConfigurationProperties("spring.datasource1")
public DataSourceProperties userDSProperties() {
return new DataSourceProperties();
}
#Primary
#Bean
public DataSource userDS(#Qualifier("userDSProperties") DataSourceProperties userDSProperties) {
return userDSProperties.initializeDataSourceBuilder().build();
}
#Bean
public LocalContainerEntityManagerFactoryBean userDSEmFactory(#Qualifier("userDS") DataSource userDS, EntityManagerFactoryBuilder builder) {
return builder.dataSource(userDS).packages(User.class).build();
}
#Primary
#Bean
public PlatformTransactionManager userDSTransactionManager(EntityManagerFactory userDSEmFactory) {
return new JpaTransactionManager(userDSEmFactory);
}
}
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackageClasses = ProductRepository.class, entityManagerFactoryRef = "productDSEmFactory", transactionManagerRef = "productDSTransactionManager")
public class ProductDBConfiguration {
#Bean
#ConfigurationProperties("spring.datasource2")
public DataSourceProperties productDSProperties() {
return new DataSourceProperties();
}
#Bean
public DataSource productDS(#Qualifier("productDSProperties") DataSourceProperties productDSProperties) {
return productDSProperties.initializeDataSourceBuilder().build();
}
#Bean
public LocalContainerEntityManagerFactoryBean productDSEmFactory(#Qualifier("productDS") DataSource productDS, EntityManagerFactoryBuilder builder) {
return builder.dataSource(productDS).packages(Product.class).build();
}
#Bean
public PlatformTransactionManager productDSTransactionManager(EntityManagerFactory productDSEmFactory) {
return new JpaTransactionManager(productDSEmFactory);
}
}
Application.properties:
spring.jpa.hibernate.ddl-auto=create
spring.jpa.generate-ddl=true
spring.datasource1.url=jdbc:mysql://localhost:3306/userdb?autoReconnect=true&useSSL=false
spring.datasource1.username=user
spring.datasource1.password=pass
spring.datasource2.url=jdbc:mysql://localhost:3306/productdb?autoReconnect=true&useSSL=false
spring.datasource2.username=user
spring.datasource2.password=pass
And a simple main app that adds some init data:
#SpringBootApplication
public class SpringDataManyDbsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataManyDbsApplication.class, args);
}
#Autowired
private UserRepository userRepository;
#Autowired
private ProductRepository productRepository;
#PostConstruct
void init () {
User user = new User("john", "doe");
userRepository.save(user);
Product product = new Product("chair", 5);
productRepository.save(product);
}
}
I tried to add the #Primary annotation to userDSEmFactory. The error goes away but the product data isn't saved anymore. Any ideas how to save this problem? I don't have a lot of experience with Spring-boot and I've read dozens of articles but many seem to do things in a different way. Thanks so much for helping me out!
update
I've added the #Primary annotation like this:
#Primary
#Bean
public LocalContainerEntityManagerFactoryBean userDSEmFactory(#Qualifier("userDS") DataSource userDS, EntityManagerFactoryBuilder builder) {
return builder.dataSource(userDS).packages(User.class).build();
}
No there are no more errors, but only the user is being saved in the primary db and nothing is being saved to the product (second) database.
So if anybody has suggestions what could be the cause of that..
You are missing #Primary annotation on your userDSEmFactory
#Primary
#Bean
public LocalContainerEntityManagerFactoryBean userDSEmFactory(#Qualifier("userDS") DataSource userDS, EntityManagerFactoryBuilder builder) {
return builder.dataSource(userDS).packages(User.class).build();
}
And also it is goot to use once #EnableTransactionManagement at your main class.

save operation in jpa data repository doesn't work when define mutiple #EnableJpaRepositories classes

I am researching on usage of Spring Data JPA. Appreciated if can help check where is wrong.
I created 2 JPA repositories: APIRepository and ClientRepository in 2 different packages and also created 2 configuration classes to configure these 2 repositories using #EnableJpaRepositories annotation respectively.
When a Spring application calls these 2 repositories' save() methods at the same time, the APIRepository.save() will fail, but without exception. If move #Primiary annotation (this is to avoid NoUniqueBeanDefinitionException) to APIAppConfig class, ClientRepository.save will fail without exception. I opened SQL log, no update SQL was executed for failing method.
did anyone hit such a situation? how to use Spring Data Jpa?
APIRepository
package test.api;
public interface APIRepository extends Repository<API, Long>{
....
}
APIAppConfig
package test.api;
#Configuration
#ComponentScan(basePackages = "test.api")
#EnableJpaRepositories(
basePackages = "test.api.repository",
entityManagerFactoryRef = "apiEntityManagerFactory",
transactionManagerRef="apiTransactionManager",
enableDefaultTransactions=true
)
#EnableTransactionManagement
public class APIAppConfig {
#Bean
public LocalContainerEntityManagerFactoryBean apiEntityManagerFactory(){
...
}
#Bean
public PlatformTransactionManager apiTransactionManager() {
...
}
#Bean
public DataSource apiDataSource() {
...
}
}
APIService
package test.api;
#Service
public class APIService {
#Autowired
private APIRepository apiRepository;
public API findOne(Long id){
return apiRepository.findOne(id);
}
#Transactional("apiTransactionManager")
public void updateOne(API api){
apiRepository.save(api);
}
}
ClientRepository
package test.client;
public interface ClientRepository extends Repository<Client, Long>{
...
}
ClientAppConfig
package test.client;
#Configuration
#ComponentScan(basePackages = "test.client")
#EnableJpaRepositories(
basePackages = "test.client",
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef="transactionManager",
enableDefaultTransactions=true
)
#EnableTransactionManagement
public class ClientAppConfig {
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
...
}
#Bean
public PlatformTransactionManager transactionManager() {
...
}
#Bean
#Primary
public DataSource dataSource() {
...
}
}
ClientService
package test.client;
#Service
public class ClientService {
#Autowired
private ClientRepository clientRepository;
public DaoTest findOne(Long id){
return clientRepository.findOne(id);
}
#Transactional("transactionManager")
public void updateOne(Client client){
clientRepository.save(client);
}
}
In your APIAppConfig class you have set
#EnableJpaRepositories(
basePackages = "test.api.repository",
But your APIRepository is in the package test.api and not in test.api.repository, at least as I can see in your APIRepository class source code.
So either change the basePackages value to reflect the correct one, or move your APIRepository inside the test.api.repository package

Getting NoUniqueBeanDefinitionException when extends QueryDslRepositorySupport and multiple datasources

I need to use multiple databases.
I am using Spring Boot + Spring Data JPA,
so I have two configuration classes:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages="com.rest.dao.first",
entityManagerFactoryRef = "firstEntityManagerFactory", transactionManagerRef = "firstTransactionManager")
public static class DnbbJdbcConfig {
#Primary
#Bean
#ConfigurationProperties(prefix="datasource.first")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Bean(name = "firstEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(dataSource())
.packages("com.rest.dao.first")
.persistenceUnit("first")
.build();
}
#Primary
#Bean(name = "firstTransactionManager")
PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactory(builder).getObject());
}
}
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages="com.rest.dao.second",
entityManagerFactoryRef = "secondEntityManagerFactory", transactionManagerRef = "secondTransactionManager")
public static class SmsJdbcConfig {
#Bean
#ConfigurationProperties(prefix="datasource.second")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "secondEntityManagerFactory")
#PersistenceContext(unitName = "second")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(dataSource())
.packages("com.rest.dao.second")
.persistenceUnit("second")
.build();
}
#Bean(name = "secondTransactionManager")
PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactory(builder).getObject());
}
}
I guess there is not error and correct.
So, when I use default repository then not error.
(e.g userRepository.findById() - not error in multi datasources)
But, When I use custom repository then error occur.
(https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations)
Custom Implements
public class FirstRepositoryImpl extends QueryDslRepositorySupport implements FirstCustomRepository {
public FirstRepositoryImpl() {
super(First.class);
}
#PersistenceContext(unitName = "first")
private EntityManager entityManager;
private QFirst first = QFirst.first;
#Override
public List<String> messages() {
JPAQuery query = new JPAQuery(entityManager);
return query.from(first).list(first.message);
}
}
ExceptionTrace
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: firstEntityManagerFactory,secondEntityManagerFactory
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:582) ~[spring-orm-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:541) ~[spring-orm-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:707) ~[spring-orm-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:680) ~[spring-orm-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:178) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:354) ~[spring-orm-4.2.3.RELEASE.jar:4.2.3.RELEASE]
... 45 common frames omitted
Did I misconfigure something?
I wrote sample code in my github repository..
https://github.com/okihouse/spring-boot-multiple-datasource-with-querydsl
Solved myself:
I'm check QueryDslRepositorySupport.class and found out.
#PersistenceContext
public void setEntityManager(EntityManager entityManager) {
Assert.notNull(entityManager);
this.querydsl = new Querydsl(entityManager, builder);
this.entityManager = entityManager;
}
#PersistenceContext have not "unitName"
So, Spring can't inject EntityManager.
I create QueryDslRepositorySupportWrapper.java
and inject EntityManager manually.
And It works.
https://github.com/okihouse/spring-boot-multiple-datasource-with-querydsl

Resources