Null pointer exception on creating Spring bean with JPA configration - java

I have Spring based application and I need to get Hibernate working. So I got inspired by this tutorial: A Guide to Hibernate with Spring 4 and I created java class(I want to configure Hibernate xml-less):
package com.mycompany.cmms.web.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
public class PersistanceJPAConfig {
#Bean
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.vsb.cmms.domain" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em.getObject();
}
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/cmms");
dataSource.setUsername( "postgres" );
dataSource.setPassword( "xxx" );
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.setProperty("hibernate.query.factory_class", "org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory");
return properties;
}
}
But when I build and start my application i get this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in com.vsb.cmms.web.config.PersistanceJPAConfig: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'entityManagerFactory' or 'persistenceUnitName' is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4717)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1404)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1394)
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.lang.IllegalArgumentException: 'entityManagerFactory' or 'persistenceUnitName' is required
at org.springframework.orm.jpa.JpaTransactionManager.afterPropertiesSet(JpaTransactionManager.java:304)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
... 21 more
The error is saying that'entityManagerFactory' or 'persistenceUnitName' is required. But entity manager factory should be provided via entityManagerFactory().
When I debbuged thi bean I noticed that em.getObject() is returning null and possibly is causing the error although I do not know why is this happening. I am using Spring 4 and Hibernate 5.2.3.Final.

Your entityManagerFactory() method really shouldn't be calling #getObject() but instead you should write it as:
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.vsb.cmms.domain" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
// just return the bean here
return em;
}
Spring handles that factory bean automatically giving your EntityManagerFactory instances.

Just found in the deeps of the internet...
If you want to make xml-less hibernate configuration with a chance easily control session(session for application or session for transaction), then you probably want to see this
Please note, the code as it is works perfectly until Hibernate 5.2 version

Related

Spring Boot says no bean named 'entityManagerFactory' available

I'm working on a new app (to me) and I received the no bean 'entityManagerFactory' available error on startup. Other people who've had this suggest it would not occur had I properly defined the data source. What confuses me is that either Spring Boot/JPA or Flyway (which I'm also using) insists on specific property names being used for your one data source. I'm not sure how someone would handle it if you had more than one. I need to change our application.properties file to fetch from environment variables so they can fetch the values from a secret. I have one definition so that flyway can do it's possible migrations. I have another so that Spring-Boot can do it's JPA based work. I have another because the existing code previously defined a dataSource and gets wired in accordingly. All are going to the same database. I wish I could use only one collection of application.properties properties, but more importantly, I want this entityManagerFactory error resolved. Because my fixes feel like a kludge, I wanted to reach out and see what I'm not understanding.
Here's the application.properties
spring.profiles.active=sprint-vault-services-not-available
spring.application.name=file-generator
file.generator.schema=FILE_GENERATOR
spring.flyway.enabled=true
spring.flyway.locations=classpath:db/migration
spring.flyway.schemas=${file.generator.schema}
spring.flyway.baseline-on-migrate=false
file-generator.date-format=MMddyy
file-generator.time-format=HHmmss
file-generator.ebcdic-output-path=app/output/ebcdic
file-generator.csv-output-path=app/output/csv
file-generator.header-timestamp-format=yyyyMMddHHmmss
file-generator.file-sequence-number=1
logging.path=app/logs
bcupload_datasource_url=${BCUPLOAD_DATASOURCE_URL}
#spring.jpa.properties.hibernate.default_schema=FILE_GENERATOR
bcupload_datasource_username=${BCUPLOAD_DATASOURCE_USERNAME}
bcupload_datasource_password=${BCUPLOAD_DATASOURCE_PASSWORD}
bcupload_datasource_driver=${BCUPLOAD_DATASOURCE_DRIVER}
bcupload_datasource_flyway_db_name=LocalFileGenerator
spring.datasource.driver-class-name=${BCUPLOAD_DATASOURCE_DRIVER}
spring.datasource.url=${BCUPLOAD_DATASOURCE_URL}
spring.datasource.password=${BCUPLOAD_DATASOURCE_PASSWORD}
spring.datasource.username=${BCUPLOAD_DATASOURCE_USERNAME}
spring.jpa.database-platform=DB2Platform
spring.jpa.show-sql=true
spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto=none
spring.flyway.url= ${BCUPLOAD_DATASOURCE_URL}
spring.flyway.user=${BCUPLOAD_DATASOURCE_USERNAME}
spring.flyway.password=${BCUPLOAD_DATASOURCE_PASSWORD}
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
2021-04-12 23:06:34 DEBUG o.s.b.d.LoggingFailureAnalysisReporter - Application failed to start due to an exception
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:814)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1282)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:297)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:330)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:113)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:691)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:508)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:374)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:134)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1699)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1444)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:623)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:611)
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:51)
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:36)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:403)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:360)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:897)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
at com.mycompany.cloud.cost.ssc.file.generator.FileGeneratorApplication.main(FileGeneratorApplication.java:22)
Bean definition of datasource:
package com.ibm.cio.cloud.cost.ssc.file.generator.configuration;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
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.orm.jpa.vendor.HibernateJpaVendorAdapter;
#Configuration
public class DataSourceConfig {
private String dataSourceUrl;
private String userName;
private String password;
private String driver;
/*
#Bean
public EntityManagerFactoryBuilder builder(Environment environment) {
Map<String, String> jpaProperties = new HashMap<>();
jpaProperties.put("hibernate.show_sql", environment.getProperty("spring.jpa.show-sql"));
jpaProperties.put("hibernate.format_sql", environment.getProperty("spring.jpa.properties.hibernate.format_sql"));
jpaProperties.put("hibernate.dialect", environment.getProperty("spring.jpa.properties.hibernate.dialect"));
return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), jpaProperties, null);
}
*/
#Autowired
public DataSourceConfig(#Value("${bcupload_datasource_url}") String bcupload_datasource_url,
#Value("${bcupload_datasource_username}") String bcupload_datasource_username,
#Value("${bcupload_datasource_password}") String bcupload_datasource_password,
#Value("${bcupload_datasource_driver}") String bcupload_datasource_driver) {
this.dataSourceUrl = bcupload_datasource_url;
this.userName = bcupload_datasource_username;
this.password = bcupload_datasource_password;
this.driver = bcupload_datasource_driver;
}
#Bean(name = "bcUploadDataSource")
public DataSource dataSource() {
return DataSourceBuilder.create()
.url(dataSourceUrl)
.username(userName)
.password(password)
.driverClassName(driver).build();
}
}
I have a project with several datasources and each datasource end up looking something like this:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
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.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
#Configuration
#EnableJpaRepositories(
basePackages = {"com.your.repositories.packages"},
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = "transactionManager")
public class DataSourceConfig{
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.entity.pacakges"});
em.setPersistenceUnitName("your_name");
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
properties.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect"));
properties.put("hibernate.show-sql", env.getProperty("spring.jpa.show-sql"));
properties.put("hibernate.temp.use_jdbc_metadata_defaults",
env.getProperty("spring.jpa.use_jdbc_metadata_defaults." + NAME));
properties.put("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName());
properties.put("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName());
em.setJpaPropertyMap(properties);
return em;
}
#Bean(name = "dataSource")
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));
dataSource.setPassword(env.getProperty("spring.datasource.password"));
return dataSource;
}
#Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManager().getObject());
return transactionManager;
}
}
So for your error, probably try to use LocalContainerEntityManagerFactoryBean instead of EntityManagerFactoryBuilder

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in "package name"

I am new to spring and hibernate as well as to stackoverflow
A developing ecommerce project using spring hibernate maven
creating two file one for frontend and 2nd for backend after creating two file i am adding dependency of backend into frontend pom.ml file
I am using java to create sessionfactory ,datasource and transaction manager
here is the code I dont understand what mistake i am doing
package com.ecom.Config;
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.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;
import
org.springframework.transaction.annotation.EnableTransactionManagement;
import com.ecom.Model.CustomerRegistration;
#Configuration
#ComponentScan("com.ecom")
#EnableTransactionManagement
public class AnnotationConfigApplicationContext {
#Bean(name = "dataSource")
public DataSource getH2DataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl("jdbc:h2:tcp://localhost/~/Ecommerce");
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUsername("sa");
dataSource.setPassword("");
return dataSource;
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "create");
return properties;
}
#Autowired
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new
LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addProperties(getHibernateProperties());
sessionBuilder.addAnnotatedClass(CustomerRegistration.class);
return sessionBuilder.buildSessionFactory();
}
#Autowired
#Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory
sessionFactory) {
HibernateTransactionManager transactionManager = new
HibernateTransactionManager(sessionFactory);
return transactionManager;
}
}
Contoller
package com.ecom.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ecom.DAO.CustomerRegDAO;
import com.ecom.Model.CustomerRegistration;
#Controller
public class CustomerRegController
{
#Autowired
private CustomerRegDAO customerRegDAO ;
#RequestMapping("/registrationForm")
public String Registration(Model theModel)
{
CustomerRegistration theCustomerRegistration = new
CustomerRegistration();
theModel.addAttribute("customer", theCustomerRegistration);
return "registration-form";
}
#RequestMapping("/saveCustomer")
public String saveCustomer(#ModelAttribute("customer")
CustomerRegistration theCustomerRegistration)
{
customerRegDAO.saveCustomer(theCustomerRegistration);
return "index";
}
}
DAO
package com.ecom.DAOImplementation;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import com.ecom.DAO.CustomerRegDAO;
import com.ecom.Model.CustomerRegistration;
#Repository("CustomerRegDAO")
#Transactional
public class CustomerRegDAOImpl implements CustomerRegDAO {
private SessionFactory sessionFactory;
#Transactional
public void saveCustomer(CustomerRegistration theCustomerRegistration) {
Session currentsession = sessionFactory.getCurrentSession();
currentsession.saveOrUpdate(theCustomerRegistration);
}
}
Error:
Type Exception Report
Message Servlet.init() for servlet [spring] threw exception
Description The server encountered an unexpected condition that prevented
it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet.init() for servlet [spring] threw
exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase
.java:475)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogVa
lve.java:651)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498)
Root cause
org.springframework.beans.factory.BeanCreationException: Error creating
bean
with name 'sessionFactory' defined in
com.ecom.Config.AnnotationConfigApplicationContext: Bean instantiation via
factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to instantiate
[org.hibernate.SessionFactory]: Factory method 'getSessionFactory' threw
exception; nested exception is java.lang.NoClassDefFoundError: Could not
initialize class
org.hibernate.annotations.common.reflection.java.JavaReflectionManager
java.lang.NoClassDefFoundError: Could not initialize class
org.hibernate.annotations.common.reflection.java.JavaReflectionManager
The exception is indicating that the class JavaReflectionManager is not found. This class is present in hibernate-commons-annotations jar file. Can you add this in your pom.xml and try running it again?
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.2.Final</version>
</dependency>

Error creating bean with name 'sessionFactory' defined in class path resource

I was trying to build a spring-mvc project without web.xml
On starting the app on the server it threw the following exception on sessionFactory.
My AppConfig.class is as follows which is used to initialize the persistence unit:
package com.myapp;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#Configuration
#ComponentScan(basePackages="com.myapp")
#EnableTransactionManagement
public class AppConfig {
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
builder
.scanPackages("com.myapp.model")
.addProperties(getHibernateProperties());
return builder.buildSessionFactory();
}
private Properties getHibernateProperties() {
Properties prop = new Properties();
prop.put("hibernate.format_sql", "true");
prop.put("hibernate.show_sql", "true");
prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return prop;
}
#Bean(name = "dataSource")
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/eventtracker");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
#Bean
public HibernateTransactionManager txManager() {
return new HibernateTransactionManager(sessionFactory());
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
And it is throwing exception :
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [com/myapp/AppConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/transaction/SystemException
Take a look at your last exception.
nested exception is java.lang.NoClassDefFoundError: javax/transaction/SystemException
It means class file javax/transaction/SystemException is not on the classpath, thus jvm complain NoClassDefFoundError
Put all of your hibernate related jar on the classpath.
It is a problem of Hibernate 5.0.6 release for Hibernate 5.0.3 everything works fine. To fix a problem add this to pom.xml (if you use Maven)
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
for Gradle build
compile group: 'javax.transaction', name: 'transaction-api', version: '1.1'
manual download
http://central.maven.org/maven2/javax/transaction/transaction-api/1.1/transaction-api-1.1.jar

nested exception is java.lang.IllegalStateException: Cannot apply class transformer without LoadTimeWeaver specified

I am facing an issue with eclipselink jpa.
Error:
HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException: Cannot generate variable name for non-typed Collection return type and an empty Collection value
type Exception report
message Request processing failed; nested exception is java.lang.IllegalArgumentException: Cannot generate variable name for non-typed Collection return type and an empty Collection value
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Cannot generate variable name for non-typed Collection return type and an empty Collection value
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.IllegalArgumentException: Cannot generate variable name for non-typed Collection return type and an empty Collection value
org.springframework.core.Conventions.getVariableNameForReturnType(Conventions.java:194)
org.springframework.web.method.annotation.ModelFactory.getNameForReturnValue(ModelFactory.java:215)
Console:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in com.config.SpringWebConfig: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot apply class transformer without LoadTimeWeaver specified
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:535)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1090)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5262)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5550)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: Cannot apply class transformer without LoadTimeWeaver specified
at org.springframework.orm.jpa.persistenceunit.SpringPersistenceUnitInfo.addTransformer(SpringPersistenceUnitInfo.java:80)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactoryImpl(PersistenceProvider.java:373)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactory(PersistenceProvider.java:313)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
... 25 more
I have following jar files.
jstl-1.2.jar
log4j-1.2.17.jar
aspectjrt-1.8.6.jar
aopalliance-1.0.jar
ojdbc6-11.2.0.3.0.jar
commons-logging-1.2.jar
persistence-api-1.0.2.jar
javax.servlet-api-3.0.1.jar
slf4j-api-1.7.12.jar
javax.persistence-2.1.0.jar
org.eclipse.persistence.antlr-2.6.1-RC1.jar
org.eclipse.persistence.asm-2.6.1-RC1.jar
org.eclipse.persistence.core-2.6.1-RC1.jar
org.eclipse.persistence.jpa.jpql-2.6.1-RC1.jar
org.eclipse.persistence.jpa-2.6.1-RC1.jar
javax.json-1.0.4.jar
jcl-over-slf4j-1.7.12.jar
spring-cloud-cloudfoundry-connector-1.2.0.RELEASE.jar
spring-cloud-core-1.2.0.RELEASE.jar
spring-cloud-spring-service-connector-1.2.0.RELEASE.jar
spring-data-commons-1.11.0.RELEASE.jar
spring-data-jpa-1.9.0.RELEASE.jar
spring-aop-4.1.7.RELEASE.jar
spring-beans-4.1.7.RELEASE.jar
spring-context-4.1.7.RELEASE.jar
spring-core-4.1.7.RELEASE.jar
spring-expression-4.1.7.RELEASE.jar
spring-jdbc-4.1.7.RELEASE.jar
spring-orm-4.1.7.RELEASE.jar
spring-tx-4.1.7.RELEASE.jar
spring-web-4.1.6.RELEASE.jar
spring-webmvc-4.1.6.RELEASE.jar
My Springwebconfig is as given below.
package com.config;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.eclipse.persistence.jpa.PersistenceProvider;
import org.springframework.context.annotation.*;
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.annotation.*;
import org.springframework.web.servlet.config.annotation.*;
#Configuration
#ComponentScan({"com.controller","com.domain","com.service","com.serviceimpl"})
#EnableWebMvc
#EnableTransactionManagement
#PropertySource("classpath:application.properties")
#EnableJpaRepositories("com.dfs.myhrtest.repo")
public class SpringWebConfig extends WebMvcConfigurerAdapter {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "eclipselink.target-database";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
private static final String PROPERTY_NAME_JPA_MAP = "eclipselink.weaving";
private static final String PROPERTY_NAME_LOAD_TIME_WEAVER = "loadTimeWeaver";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(PersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
entityManagerFactoryBean.setJpaProperties(hibProperties());
return entityManagerFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(PROPERTY_NAME_JPA_MAP, env.getRequiredProperty(PROPERTY_NAME_JPA_MAP));
properties.put(PROPERTY_NAME_LOAD_TIME_WEAVER, env.getRequiredProperty(PROPERTY_NAME_LOAD_TIME_WEAVER));
return properties;
}
#Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("/");
}
/*#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}*/
}
Properties file
#DB properties:
db.driver=oracle.jdbc.driver.OracleDriver
db.url=jdbc:oracle:kkkkkkkkkkkkkkkkkkkkkk
db.username=jjjjjjj
db.password=kkkkkkkkkk!d
#Hibernate Configuration:
eclipselink.target-database=Oracle
hibernate.show_sql=true
entitymanager.packages.to.scan=com.domain
eclipselink.weaving=static;
loadTimeWeaver=org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver
I have tried with weaving = false/true and static. Still The error is same. Please let me know if any one needs more details.
It would be great if anyone can help me. I am stuck...

creating transactionmanager and entity manager via configuration class

i am relatively new to spring and want to implement the spring jpa with mysql. below mentioned is my configurations...
<beans ...
<context:component-scan base-package="com.pg" />
<mvc:annotation-driven />
<tx:annotation-driven/>
<aop:aspectj-autoproxy />
<jpa:repositories base-package="com.pg.dao" /> ...
My configuation class to create the datasource, transactionmanager and entitymanager is listed below.
package com.pg.conf;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import javax.transaction.TransactionManager;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
#Configuration
public class JPAConfiguration {
#Bean
public DataSource dataSource(){
BasicDataSource datasource = new BasicDataSource();
datasource.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
datasource.setUrl("jdbc:mydql://localhost:3306/pg1");
datasource.setUsername("root");
datasource.setPassword("root");
return datasource;
}
#Bean
public **FactoryBean<EntityManagerFactory>** entityManagerFactory(){
LocalContainerEntityManagerFactoryBean containerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
containerEntityManagerFactoryBean.setDataSource(dataSource());
HibernateJpaVendorAdapter adaptor = new HibernateJpaVendorAdapter();
containerEntityManagerFactoryBean.setJpaVendorAdapter(adaptor);
containerEntityManagerFactoryBean.setPackagesToScan("com.pg.entity");
Properties props = new Properties();
props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
props.setProperty("hibernate.show_sql", "true");
containerEntityManagerFactoryBean.setJpaProperties(props);
return containerEntityManagerFactoryBean;
}
#Bean
public TransactionManager transactionManager(){
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setDataSource(dataSource());
**jpaTransactionManager.setEntityManagerFactory(entityManagerFactory());**
return transactionManager();
}
}
i have error on the line jpaTransactionManager.setEntityManagerFactory(entityManagerFactory());
i think the returntype of the entitymanager method is not correct... even though it does not show error....
Any help is appreciated.
Start with reading the Spring reference guide and read about FactoryBeans.
Then change your code accordingly.
#Bean
public TransactionManager transactionManager(EntityManagerFactory entityManagerFactory){
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setDataSource(dataSource());
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory);
return jpaTransactionManager;
}
Replace
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory());
with
jpaTransactionManager.setEntityManagerFactory((EntityManagerFactory) entityManagerFactory());

Categories