jpa not started with websphere - NoClassDefFoundError: CandidateComponentsIndexLoader? - spring

There is spring 4.3.0 application + jpa + jaxb
So, I need to start this application on websphere server.
My application consist of main class - WebApplicationInitializer
There 3 layers - web(controllers with WebConfig), service(ServiceConfig) and persisntence(PersistenceConfig)
After I add PersistenceConfig in application - there is error message on WAS server(there is no such problems on tomcat server)
My PersisntenceConfig:
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
#EnableTransactionManagement
#EnableJpaAuditing
#EnableJpaRepositories(basePackages = {"data.persistence"})
#PropertySource("classpath:application.properties")
#ComponentScan(basePackages = {"data.persistence"})
public class PersistenceConfig {
private static final String PROP_DATABASE_DRIVER = "db.driver";
private static final String PROP_DATABASE_URL = "db.url";
private static final String PROP_DATABASE_USERNAME = "db.username";
private static final String PROP_DATABASE_PASSWORD = "db.password";
private static final String PROP_HIBERNATE_DIALECT = "db.hibernate.dialect";
private static final String PROP_HIBERNATE_SHOW_SQL = "db.hibernate.show_sql";
private static final String PACKAGE_WITH_JPA_ENTITIES = "ru.sbrf.risks.services.data.persistence";
private static final String PROP_HIBERNATE_HBM2DDL_AUTO = "db.hibernate.hbm2ddl.auto";
private static final String DO_NOT_AUDIT_LOCKING_FIELD = "org.hibernate.envers.do_not_audit_optimistic_locking_field";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROP_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROP_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROP_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROP_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
entityManager.setDataSource(dataSource());
entityManager.setPackagesToScan(PACKAGE_WITH_JPA_ENTITIES);
entityManager.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManager.setJpaProperties(getHibernateProperties());
return entityManager;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
//Set properties hibernate
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", env.getRequiredProperty(PROP_HIBERNATE_DIALECT));
properties.put("hibernate.show_sql", env.getRequiredProperty(PROP_HIBERNATE_SHOW_SQL));
properties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty(PROP_HIBERNATE_HBM2DDL_AUTO));
properties.put("org.hibernate.envers.do_not_audit_optimistic_locking_field",
env.getRequiredProperty(DO_NOT_AUDIT_LOCKING_FIELD));
properties.put("verifyServerCertificate", false);
properties.put("useSSL", false);
properties.put("requireSSL", false);
properties.put("useLegacyDatetimeCode", false);
properties.put("useUnicode", "yes");
properties.put("characterEncoding", "UTF-8");
properties.put("serverTimezone", "UTC");
properties.put("useJDBCCompliantTimezoneShift", true);
return properties;
}
}
Error message is :
Caused by: java.lang.NoClassDefFoundError:
org.springframework.context.index.CandidateComponentsIndexLoader
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.setResourceLoader(DefaultPersistenceUnitManager.java:431)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.setResourceLoader(LocalContainerEntityManagerFactoryBean.java:320)
at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:112)
at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:97)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
... 113 more Caused by: java.lang.ClassNotFoundException: org.springframework.context.index.CandidateComponentsIndexLoader
at java.net.URLClassLoader.findClass(URLClassLoader.java:609)
at com.ibm.ws.bootstrap.ExtClassLoader.findClass(ExtClassLoader.java:243)
at java.lang.ClassLoader.loadClassHelper(ClassLoader.java:924)
at java.lang.ClassLoader.loadClass(ClassLoader.java:869)
at com.ibm.ws.bootstrap.ExtClassLoader.loadClass(ExtClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:852)
at com.ibm.ws.classloader.ProtectionClassLoader.loadClass(ProtectionClassLoader.java:62)
at com.ibm.ws.classloader.ProtectionClassLoader.loadClass(ProtectionClassLoader.java:58)
at com.ibm.ws.classloader.CompoundClassLoader.loadClass(CompoundClassLoader.java:586)
at java.lang.ClassLoader.loadClass(ClassLoader.java:852)
at com.ibm.ws.classloader.CompoundClassLoader.loadClass(CompoundClassLoader.java:586)
at java.lang.ClassLoader.loadClass(ClassLoader.java:852)
... 120 more
[12/11/18 14:10:06:443 MSK] 00000079 webapp I
com.ibm.ws.webcontainer.webapp.WebApp log SRVE0292I: Servlet Message -
[MyApp_war#MyApp.war]:.Closing Spring root WebApplicationContext
[12/11/18 14:10:06:445 MSK] 00000079 webapp E
com.ibm.ws.webcontainer.webapp.WebGroupImpl WebGroup SRVE0015E:
Failure to initialize Web application MyApp.war [12/11/18 14:10:06:447
MSK] 00000079 DeployedAppli W WSVR0206E: Module, MyApp.war, of
application, MyApp_war.ear/deployments/MyApp_war, failed to start
[12/11/18 14:10:06:448 MSK] 00000079 ApplicationMg W WSVR0101W: An
error occurred starting, MyApp_war [12/11/18 14:10:06:448 MSK]
00000079 ApplicationMg A WSVR0217I: Stopping application: MyApp_war
[12/11/18 14:10:06:455 MSK] 00000079 ApplicationMg A WSVR0220I:
Application stopped: MyApp_war [12/11/18 14:10:06:457 MSK] 00000079
CompositionUn E WSVR0194E: Composition unit
WebSphere:cuname=MyApp_war in BLA WebSphere:blaname=MyApp_war failed
to start. [12/11/18 14:10:06:461 MSK] 00000079 MBeanHelper E Could
not invoke an operation on object:
WebSphere:name=ApplicationManager,process=server1,platform=proxy,node=pega-wasNode01,version=8.5.5.13,type=ApplicationManager,mbeanIdentifier=ApplicationManager,cell=pega-wasNode01Cell,spec=1.0
because of an mbean exception: com.ibm.ws.exception.RuntimeWarning:
com.ibm.ws.webcontainer.exception.WebAppNotLoadedException: Failed to
load webapp: Failed to load webapp: Error creating bean with name
'entityManagerFactory' defined in
data.persistence.PersistenceConfig: Initialization of bean
failed; nested exception is
java.lang.NoClassDefFoundError:
org.springframework.context.index.CandidateComponentsIndexLoader

The class org.springframework.context.index.CandidateComponentsIndexLoader is a introduced in Spring Framework 5.0. You state you are using Spring Framework 4.3.
The logical conclusion is you are mixing jars from different versions of Spring. As a rule of thumb never mix jars from different versions of a framework.

Related

Spring boot Multi-module project multi-datasource

I'm trying to develop a multi-module spring boot project with multi-datasource connection. I have separate this project in 5 modules:
-springboot-multiple-maven-modules:
1. domain -> database2's model
2. domain2 -> database2's model
3. persistence -> database1's persistence
4. persistence2 -> database2's persistence
5. web -> Access to database1 and database2
You can download the code in the following link:
GitHub Project
I've configure both datasource in this way:
- database1:
package rc.persistence;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "hotelEntityManagerFactory", transactionManagerRef = "hotelTransactionManager", basePackages = {
"rc.repository" }) //Mirar si se puede sustituir por rc.domain o rc.repository
public class HotelDbConfig {
#Autowired
private Environment env;
#Bean(name = "hotelDataSource")
#ConfigurationProperties(prefix = "hoteles.datasource")
public DataSource customDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("hoteles.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("hoteles.datasource.url"));
dataSource.setUsername(env.getProperty("hoteles.datasource.username"));
dataSource.setPassword(env.getProperty("hoteles.datasource.password"));
return dataSource;
}
#Bean(name = "hotelEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("hotelDataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("rc.domain")
.persistenceUnit("hotel").build();
}
#Bean(name = "hotelTransactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("hotelEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
database2:
package rc.persistence2;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "cocheEntityManagerFactory", transactionManagerRef = "cocheTransactionManager", basePackages = {
"rc.repository2" })
public class CocheDbConfig {
#Autowired
private Environment env;
#Primary
#Bean(name = "cocheDataSource")
#ConfigurationProperties(prefix = "coches.datasource")
public DataSource customDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("coches.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("coches.datasource.url"));
dataSource.setUsername(env.getProperty("coches.datasource.username"));
dataSource.setPassword(env.getProperty("coches.datasource.password"));
return dataSource;
}
#Primary
#Bean(name = "cocheEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("cocheDataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("rc.domain2")
.persistenceUnit("coche").build();
}
#Primary
#Bean(name = "cocheTransactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("cocheEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
But when I try to use repositories from web module:
package rc.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import rc.domain2.Coche;
import rc.persistence2.CocheRepository;
#RestController
public class CocheController {
#Autowired
private CocheRepository cocheRepository;
public CocheController(CocheRepository cocheRepository) {
this.cocheRepository = cocheRepository;
}
#GetMapping(value = "/coches")
public List<Coche> getCoches() {
List<Coche> hotels = this.cocheRepository.findAll();
return hotels;
}
}
It shows me the following error:
I've tried differents possibilities but always the same result:
2018-09-27 17:08:58.399 WARN 15272 --- [ main]
ConfigServletWebServerApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'cocheController' defined in file
[C:\springboot-multiple-maven-modules\web\target\classes\rc\web\CocheController.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'rc.persistence2.CocheRepository' available:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {} 2018-09-27 17:08:58.399 INFO 15272 --- [
main] j.LocalContainerEntityManagerFactoryBean : Closing JPA
EntityManagerFactory for persistence unit 'coche' 2018-09-27
17:08:58.400 INFO 15272 --- [ main]
j.LocalContainerEntityManagerFactoryBean : Closing JPA
EntityManagerFactory for persistence unit 'hotel' 2018-09-27
17:08:58.403 INFO 15272 --- [ main]
o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-09-27 17:08:58.421 INFO 15272 --- [ main]
ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report
re-run your application with 'debug' enabled. 2018-09-27 17:08:58.670
ERROR 15272 --- [ main]
o.s.b.d.LoggingFailureAnalysisReporter :
*************************** APPLICATION FAILED TO START
Description:
Parameter 0 of constructor in rc.web.CocheController required a bean
of type 'rc.persistence2.CocheRepository' that could not be found.
Action:
Consider defining a bean of type 'rc.persistence2.CocheRepository' in
your configuration.
Please help!!
Thanks in advance!
You got a error in the datasource configuration. Your CocheDbConfig datasource is scanning in the based packages "rc.repository2" to find out Repository class so it can't find the bean 'rc.persistence2.CocheRepository' in your controller.
You should change the based packages in your database2 datasource like this
#EnableJpaRepositories(entityManagerFactoryRef = "cocheEntityManagerFactory", transactionManagerRef = "cocheTransactionManager", basePackages = {
"rc.persistence2" })

In Spring Rest annotation based CRUD application , but getting the following exception

enter image description herePlease help me how to resolve the following exception.
enter image description here
Following is my hibernate cinfiguration file,
package com.springrest.annotationbased.crudexampleapplication.configuration;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#ComponentScan({ "com.springrest.annotationbased.crudexampleapplication.configuration" })
#PropertySource(value = "classpath:applicaton.properties" )
public class HibernateConfiguration {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String []{ "com.springrest.annotationbased.crudexampleapplication.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource ();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource();
}
public Properties hibernateProperties(){
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hiberante.hbm2dll.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
return properties;
}
#Bean
#Autowired //SessionFactory obj need to be injected as dependent in HibernateTransactionManager to provide support for the transaction for the sessions created by SessionFactory
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory){
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
}
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.springrest.annotationbased.crudexampleapplication.configuration.HibernateConfiguration]; nested exception is java.io.FileNotFoundException: class path resource [applicaton.properties] cannot be opened because it does not exist
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:181)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:321)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:673)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:519)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4851)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: class path resource [applicaton.properties] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
at org.springframework.core.io.support.EncodedResource.getInputStream(EncodedResource.java:153)
at org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(PropertiesLoaderUtils.java:98)
at org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(PropertiesLoaderUtils.java:72)
at org.springframework.core.io.support.PropertiesLoaderUtils.loadProperties(PropertiesLoaderUtils.java:58)
at org.springframework.core.io.support.ResourcePropertySource.<init>(ResourcePropertySource.java:84)
at org.springframework.context.annotation.ConfigurationClassParser.processPropertySource(ConfigurationClassParser.java:360)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:254)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:231)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:198)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:167)
... 18 more
Change the value from classpath:applicaton.properties to classpath:application.properties
in HibernateConfiguration in line (application instead of applicaton):
#PropertySource(value = "classpath:applicaton.properties" )
Looks like a typo.

Spring Boot Embedded Tomcat - No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found 3

I am working on my spring boot application and running with embedded tomcat 8.x. I am trying to configure three different oracle data sources using JNDI and followed this link. Below are my different files:
application-dev.properties
spring.oracle.datasource.oracleDS1.jndi-name=jdbc/oracleDS1
spring.oracle.datasource.oracleDS2.jndi-name=jdbc/oracleDS2
spring.oracle.datasource.oracleDS3.jndi-name=jdbc/oracleDS3
OracleDataSourceConfiguration
package com.adp.orbis.requesttracker.orbisrequesttracker;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
#Configuration
public class OracleDataSourceConfiguration {
#Value("${spring.oracle.datasource.oracleDS1.jndi-name}")
private String oracleDS1;
#Value("${spring.oracle.datasource.oracleDS2.jndi-name}")
private String oracleDS2;
#Value("${spring.oracle.datasource.oracleDS3.jndi-name}")
private String oracleDS3;
#Bean(name="dataSource1", destroyMethod = "")
#Profile("dev")
#Primary
public DataSource evolutionDataSource() {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource(oracleDS1);
}
#Bean(name="dataSource2", destroyMethod = "")
#Profile("dev")
#Primary
public DataSource orbisQueryOnlyDataSource() {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource(oracleDS2);
}
#Bean(name="dataSource3", destroyMethod = "")
#Profile("dev")
public DataSource orbisExportDataSource() {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource(oracleDS3);
}
}
TomcatEmbeddedServletContainerFactory
#Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
return new TomcatEmbeddedServletContainerFactory() {
#Override
protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) {
tomcat.enableNaming();
return super.getTomcatEmbeddedServletContainer(tomcat);
}
#Override
protected void postProcessContext(Context context) {
ContextResource oracleDS1JNDIResource = new ContextResource();
oracleDS1JNDIResource.setName("jdbc/oracleDS1");
oracleDS1JNDIResource.setType(DataSource.class.getName());
oracleDS1JNDIResource.setProperty("driverClassName", "oracle.jdbc.driver.OracleDriver");
oracleDS1JNDIResource.setProperty("url", "jdbc:oracle:thin:#localhost:1521/mydbservice1");
oracleDS1JNDIResource.setProperty("username", "db-user-name");
oracleDS1JNDIResource.setProperty("password", "db-user-pass");
oracleDS1JNDIResource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory");
context.getNamingResources().addResource(oracleDS1JNDIResource);
ContextResource oracleDS2JNDIResource = new ContextResource();
oracleDS2JNDIResource.setName("jdbc/oracleDS2");
oracleDS2JNDIResource.setType(DataSource.class.getName());
oracleDS2JNDIResource.setProperty("driverClassName", "oracle.jdbc.driver.OracleDriver");
oracleDS2JNDIResource.setProperty("url", "jdbc:oracle:thin:#localhost:1521/mydbservice2");
oracleDS2JNDIResource.setProperty("username", "db-user-name");
oracleDS2JNDIResource.setProperty("password", "db-user-pass");
oracleDS2JNDIResource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory");
context.getNamingResources().addResource(oracleDS2JNDIResource);
ContextResource oracleDS3JNDIResource = new ContextResource();
oracleDS3JNDIResource.setName("jdbc/oracleDS3");
oracleDS3JNDIResource.setType(DataSource.class.getName());
oracleDS3JNDIResource.setProperty("driverClassName", "oracle.jdbc.driver.OracleDriver");
oracleDS3JNDIResource.setProperty("url", "jdbc:oracle:thin:#localhost:1521/mydbservice3");
oracleDS3JNDIResource.setProperty("username", "db-user-name");
oracleDS3JNDIResource.setProperty("password", "db-user-pass");
oracleDS3JNDIResource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory");
context.getNamingResources().addResource(oracleDS3JNDIResource);
}
};
}
But when I run this spring boot application, it throws below exception. Could you please help me what I am missing here? I tried adding #Primary with all DataSource bean. But no luck.
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found 3: dataSource1,dataSource2,dataSource3
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found 3: dataSource1,dataSource2,dataSource3
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1041) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:345) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:340) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1092) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.init(DataSourceInitializer.java:77) ~[spring-boot-autoconfigure-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_112]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_112]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_112]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_112]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:311) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:134) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
... 38 common frames omitted
There should be atleast 1 bean with name dataSource. So either replace any one of the existing bean with name for exp dataSource1 to dataSource, or create a new one.
Trying to say, change
#Bean(name="dataSource1", destroyMethod = "")
#Profile("dev")
#Primary
public DataSource evolutionDataSource() {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource(oracleDS1);
}
To
#Bean(name="dataSource", destroyMethod = "")
#Profile("dev")
#Primary
public DataSource evolutionDataSource() {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource(oracleDS1);
}
OR Simply remove #Primary from any of the existing dataSource* beans. At most 1 bean can have #Primary under same #Profile
I am able to resolve this issue. The problem was, I had defined all data sources in my spring boot application and it was also importing dependent spring context file. That means, I had same data sources configured into my imported spring context file too. I removed all data source beans from OracleDataSourceConfiguration(as mentioned in my question on top) and used TomcatEmbeddedServletContainerFactory to initialize JNDI data sources (referred this) with the same name which are mentioned in my imported spring context file. It worked for me.
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/myDataSource" />

Spring Java Config Error creating bean with name 'entityManagerFactory' defined in class path resource

I'm trying to convert the xml application configuration files to Java based configuration.
I'm encountering a problem with the entityManager. It worked well with persistence.xml and web.xml
<!-- Entity Manager -->
<jee:jndi-lookup id="entityManagerFactory" jndi-name="jdbc/derby"></jee:jndi-lookup>
I use
Spring 3.2
maven 3
Java 7
glassfish embedded 3.1.1
Spring Data JPA 1.4.2
Could you help me ? Thank you !
Stack trace
mai 27, 2014 11:19:57 PM org.apache.catalina.core.ContainerBase addChildInternal
Grave: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/marc/embeddedglassfish/config/PersistenceContext.class]: Invocation of init method failed; nested exception is java.lang.reflect.UndeclaredThrowableException
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5389)
at com.sun.enterprise.web.WebModule.start(WebModule.java:498)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:917)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:901)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:733)
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2000)
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1651)
at com.sun.enterprise.web.WebApplication.start(WebApplication.java:109)
at org.glassfish.internal.data.EngineRef.start(EngineRef.java:130)
at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:269)
at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:294)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:462)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:382)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:355)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:370)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1064)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:96)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1244)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1232)
at com.sun.enterprise.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:129)
at com.sun.enterprise.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:105)
at org.glassfish.maven.PluginUtil.doDeploy(PluginUtil.java:106)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.maven.AbstractDeployMojo.doDeploy(AbstractDeployMojo.java:239)
at org.glassfish.maven.RunMojo.execute(RunMojo.java:68)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:107)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:534)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/marc/embeddedglassfish/config/PersistenceContext.class]: Invocation of init method failed; nested exception is java.lang.reflect.UndeclaredThrowableException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1486)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1117)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:922)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
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.contextListenerStart(StandardContext.java:4750)
at com.sun.enterprise.web.WebModule.contextListenerStart(WebModule.java:550)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5366)
... 49 more
Caused by: java.lang.reflect.UndeclaredThrowableException
at com.sun.proxy.$Proxy147.addTransformer(Unknown Source)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactory(PersistenceProvider.java:231)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:287)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1483)
... 64 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager$Jpa2PersistenceUnitInfoDecorator.invoke(DefaultPersistenceUnitManager.java:617)
... 70 more
Caused by: java.lang.IllegalStateException: Cannot apply class transformer without LoadTimeWeaver specified
at org.springframework.orm.jpa.persistenceunit.SpringPersistenceUnitInfo.addTransformer(SpringPersistenceUnitInfo.java:109)
... 75 more
PersistenceContext.java
package com.marc.embeddedglassfish.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
import com.marc.springmvc3.dao.PersonDAO;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {"com.marc.springmvc3.repositories"})
public class PersistenceContext {
/* glassfish requires "java:app/"
Deployment Descriptor. An application-scoped resource is defined in the glassfish-resources.xml deployment descriptor file.
This file is placed in the META-INF directory of the module or application archive. For web applications or modules,
this file is placed in the WEB-INF directory. If any submodule archives of an enterprise application archive have their
own glassfish-resources.xml files, the resource definitions are scoped to those modules only. For more information about
the glassfish-resources.xml file, see Appendix B, GlassFish Server Deployment Descriptor Files and Appendix C, Elements of the
GlassFish Server Deployment Descriptors.
Naming. Application-scoped resource JNDI names begin with java:app or java:module. If one of these prefixes is not specified
in the JNDI name, it is added. For example, application-scoped databases have JNDI names in the following format:
java:app/jdbc/DataSourceName or java:module/jdbc/DataSourceName. This is in accordance with the naming scopes introduced
in the Java EE 6 Specification.
http://docs.oracle.com/cd/E18930_01/html/821-2417/giydj.html
oracle glassfish application deployment guide
*/
#Bean
public DataSource dataSource() {
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(true);
DataSource dataSource = dsLookup.getDataSource("java:app/jdbc/TestDB");
return dataSource;
}
#Bean
public PersonDAO personDao() {
PersonDAO personDao = new PersonDAO();
personDao.setDataSource(dataSource());
return personDao;
}
#Bean
public AbstractPlatformTransactionManager transactionManager() {
return new JpaTransactionManager(entityManagerFactory());
}
#Bean
public DataSource dataSourceForEntityManager() {
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(true);
// "jdbc/__TimerPool" is defined by default in embedded glassfish
DataSource dataSource = dsLookup.getDataSource("jdbc/__TimerPool");
return dataSource;
}
#Bean
public EntityManagerFactory entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
EclipseLinkJpaVendorAdapter vendor = new EclipseLinkJpaVendorAdapter();
vendor.setDatabase(Database.DERBY);
vendor.setGenerateDdl(true);
vendor.setShowSql(true);
entityManagerFactoryBean.setJpaVendorAdapter(vendor);
entityManagerFactoryBean.setJtaDataSource(dataSourceForEntityManager());
entityManagerFactoryBean.setPackagesToScan(new String[] { "com.marc.springmvc3.model" });
final Properties props = new Properties();
props.setProperty("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.EmbeddedDriver");
props.setProperty("eclipselink.target-database", "DERBY");
props.setProperty("eclipselink.ddl-generation", "drop-and-create-table");
props.setProperty("eclipselink.logging.level.sql", "FINEST");
props.setProperty("eclipselink.logging.parameters", "true");
entityManagerFactoryBean.setJpaProperties(props);
entityManagerFactoryBean.afterPropertiesSet();
return entityManagerFactoryBean.getObject();
}
}
PersonService.java
package com.marc.springmvc3.service;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import com.marc.springmvc3.model.Person;
import com.marc.springmvc3.repositories.PersonRepository;
#Service
public class PersonService {
#Inject
private PersonRepository repository;
#Inject
private List<Person> persons;
public List<Person> getAllPersons() {
Person person = new Person();
person.setFirstName("Lucky");
person.setName("Luke");
repository.save(person);
person.setFirstName("");
person.setName("");
Person dbPerson = repository.findOne(person.getId());
persons.add(dbPerson);
return persons;
}
}
PersonRepository.java
package com.marc.springmvc3.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.marc.springmvc3.model.Person;
public interface PersonRepository extends JpaRepository<Person, Integer> {
}
Initiliazer
package com.marc.embeddedglassfish.initializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class EmbeddedGlassfishInitializer implements WebApplicationInitializer {
private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
private static final String DISPATCHER_SERVLET_MAPPING = "/";
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.marc.embeddedglassfish.config");
return context;
}
}
I solved it
The interesting part of the stack trace is at the end:
Caused by: java.lang.IllegalStateException: Cannot apply class transformer without LoadTimeWeaver specified
The explaination here helped me : EclipseLinkJpaVendorAdapter instead of HibernateJpaVendorAdapter issue
I still don't know how to get an EntitManagerFactory from glassfish as JNDI in the Java based application context configuration. Any idea ?
It should be:
#Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory() {
...
entityManagerFactoryBean.setJpaProperties(props);
return entityManagerFactoryBean;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
It's not recommended to instantiate any FactoryBean directly from code: there is need just rely on Spring contaier.
To use a FactoryBean result it is nessary to follow with parameter injection strategy.

org.hibernate.HibernateException: Dialect class not found: org.hibernate.dialect.MySQLDialect in spring MVC

i am using Spring’s WebApplicationInitializer interface to create the application context programmatically and using hibernate with jpa specification for data persistence. i put db.properties file in src folder adding #PropertySource("classpath:db.properties") in WebAppConfig class. i have following jars for hibernate in classpath.............
antlr-2.7.7.jar aopalliance-1.0.jar
commons-dbcp-1.4-javadoc.jar
commons-dbcp-1.4-sources.jar
commons-dbcp-1.4.jar
commons-logging-1.1.1.jar
commons-pool-1.6-javadoc.jar
commons-pool-1.6-sources.jar
commons-pool-1.6.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.1.Final.jar
hibernate-core-4.1.9.Final.jar
hibernate-entitymanager-4.1.9.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.17.1-GA.jar
jboss-logging-3.1.0.GA.jar
jta-1.1.jar
mysql-connector-java-5.1.6-bin.jar
web initialzer class code
package com.genesis.init;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class Initializer implements WebApplicationInitializer {
// gets invoked automatically when application starts up
public void onStartup(ServletContext servletContext)
throws ServletException {
// Create ApplicationContext. I'm using the
// AnnotationConfigWebApplicationContext to avoid using beans xml files.
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebAppConfig.class);
// Add the servlet mapping manually and make it initialize automatically
Dynamic servlet = servletContext.addServlet("dispatcher",
new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
WebAppConfig code
package com.genesis.init;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
// specifies this class as configuration
#ComponentScan("com.genesis")
// specifies which package to scan
#EnableWebMvc
// enable spring web mvc to use annotation
#PropertySource("classpath:db.properties")
// plugs in property file which located in the resource folder.
#EnableTransactionManagement
// enables Spring’s annotation-driven transaction management capability.
public class WebAppConfig extends WebMvcConfigurerAdapter {
#Autowired
private Environment env;
// Tell SpingMVC where to find view scripts
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
// Enable serving static resources even when DispatcherServlet is mapped to
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
// Enable accessing entityManager from view scripts. Required when using
// lazy loading
#Override
public void addInterceptors(InterceptorRegistry registry) {
OpenEntityManagerInViewInterceptor viewInterceptor = new OpenEntityManagerInViewInterceptor();
viewInterceptor.setEntityManagerFactory(entityManagerFactory().getObject());
registry.addWebRequestInterceptor(viewInterceptor);
}
//Set up dataSource to be used by Hibernate. Also make sure the connection doesn't go down
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl(env.getProperty("url"));
dataSource.setDriverClassName(env.getProperty("driver"));
dataSource.setUsername(env.getProperty("user"));
dataSource.setPassword(env.getProperty("pass"));
dataSource.setValidationQueryTimeout(5);
return dataSource;
}
//Set up JPA and transactionManager
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(getDataSource());
emf.setPackagesToScan("com.genesis.model");
// let Hibernate know which database we're using.
// note that this is vendor specific, not JPA
Map<String, Object> opts = emf.getJpaPropertyMap();
opts.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
emf.setJpaVendorAdapter(va);
return emf;
}
//Let us use PlatformTransactionManager directly to implement programmatic approach to implement transactions
//To start a new transaction you need to have a instance of TransactionDefinition
#Bean
public PlatformTransactionManager transactionManager(){
JpaTransactionManager transactionManager=new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager();
}
}
database property file is as.
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
hibernate.dialect=org.hibernate.dialect.MySQLDialect
user=root
pass=iems1234
show_sql=true
packages.to.scan=com.genesis.model
console output is...........
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class com.genesis.init.WebAppConfig: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1507)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1145)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:922)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:493)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:512)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:466)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1267)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1084)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3920)
at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:426)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1345)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1530)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1519)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:890)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:293)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:317)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1566)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1503)
... 27 more
Caused by: org.hibernate.HibernateException: Dialect class not found: org.hibernate.dialect.MySQLDialect
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.constructDialect(DialectFactoryImpl.java:76)
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:64)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:170)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:77)
at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2283)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2279)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1748)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:905)
... 33 more
Caused by: org.hibernate.service.classloading.spi.ClassLoadingException: Unable to load class [org.hibernate.dialect.MySQLDialect ]
at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:141)
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.constructDialect(DialectFactoryImpl.java:73)
... 44 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.hibernate.dialect.MySQLDialect
at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl$1.findClass(ClassLoaderServiceImpl.java:99)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:266)
at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:138)
... 45 more
You aren't using Maven or Gradle as a build tool, so you will have to make sure that all of your needed jar files are in the WEB-INF/lib directory of your web application. If it isn't in that directory it isn't on the classpath.
I strongly suggest using one of the earlier mentioned build tools to build your artifact and manage your dependencies. It will save you a lot of searching and headaches.
Links
Maven
Gradle

Resources