JPA No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined - spring

I have a JPA/spring/hibernate application deployed on Tomcat 8. But when the tomcat server startup i can see this warning message "No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined". Help would be appreciated because i have no idea about the configuration error.
persistence.xml
<persistence-unit name="persistenceUnit"
transaction-type="RESOURCE_LOCAL">
...
spring context files are defined into several files for reusability
context-ds.xml
<bean id="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource" />
<property name="persistenceUnitName" value="persistenceUnit" />
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManager" />
</bean>
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
...
context-config.xml
<context:annotation-config />
<context:component-scan base-package="com.app" />
<jpa:repositories base-package="com.app" />
<tx:annotation-driven transaction-manager="txManager"
order="200" />
and web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/context-config.xml, /WEB-INF/context-ds.xml, /WEB-INF/context-dao.xml</param-value>
</context-param>
and DAO abstract class defines the PersistenceContext annotation
#PersistenceContext
protected EntityManager entityManager;
Real message
11:45:18.710 [localhost-startStop-1] WARN AbstractBeanFactory.getTypeForFactoryBean - Bean creation exception on FactoryBean type check: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDAO' defined in ServletContext resource [/WEB-INF/context-dao.xml]: Cannot create inner bean 'genericDao$child#632cb33' of type [com.app.dao.GenericDaoImpl] while setting bean property 'target'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'genericDao$child#632cb33': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
if i declare PersistenceContext like this, i have the message No bean named 'persistenceUnit' is defined
#PersistenceContext(unitName="persistenceUnit")
protected EntityManager entityManager;

you have to define in an #Configuration annotated class a bean like this... a nd name it accordingly to your ref
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = null;
try {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
vendorAdapter.setDatabasePlatform(MyAppSettings.getDbPlattform());
HibernateJpaDialect jpd = new HibernateJpaDialect();
factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaDialect(jpd);
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(MyAppSettings.packagesToScan);
factory.setDataSource(MyDataSource());
} catch (SQLException e) {
e.printStackTrace();
}
return factory;
}
edit:
maybe your spring config xml isnt included into component scan
try :
#ImportResource("classpath:spring-config.xml")
....please post the full stacjtrace of you eception..

Related

Unable to locate a ejb in spring context

I am trying to use a EJB singleton bean inside of spring bean but somehow it unable to locate a this ejb and getting a message when run a server:
SEVERE: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationFailureHandler' defined in class path resource [spring-security-config.xml]: Cannot resolve reference to bean 'loginAttemptService' while setting bean property 'loginAttemptService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'loginAttemptService' is defined
Here is a EJB:
public interface ILoginAttemptService {
public boolean checkout(String username);
}
Here is implementation:
#Slf4j
#Stateless(name = "loginAttemptService")
#Singleton
public class LoginAttemptsService implements ILoginAttemptService {
..
}
In spring framework this is how i define a stateless bean:
<bean id="loginAttemptServiceBean"
class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean">
<property name="jndiName"
value="java:app/osloproject-ejb/loginAttemptService"/>
<property name="businessInterface"
value="com.hospitality.hp.securitycommons.api.ILoginAttemptService"/>
</bean>
<bean id="authSuccessHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="redirectStrategy">
<bean class="com.hospitality.hp.securitycommons.tools.spring.CORSCompatibleTwoFactorAuthenticationRedirectStrategy">
<property name="loginAttemptService" ref="loginAttemptServiceBean"/>
</bean>
</property>
</bean>
<bean id="authenticationFailureHandler"
class="com.hospitality.hp.securitycommons.tools.spring.AuthenticationFailureCustomHandler">
<property name="useForward" value="true"/>
<property name="defaultFailureUrl" value="/login.jsp"/>
<property name="loginAttemptService" ref="loginAttemptServiceBean"/>
</bean>
Can someone tell me why it unable to find the JNDI name of this EJB ?
try
<jee:local-slsb id="loginAttemptServiceBean" jndi-name="java:app/osloproject-ejb/loginAttemptService"
business-interface="com.hospitality.hp.securitycommons.api.ILoginAttemptService"/>
"jee" is Spring’s namespace.and also check the jndi-name value is correct

Error creating bean with name 'vehicleDao': Injection of autowired dependencies failed:Could not autowire field:

Hii iam doing spring ORM with hibernate. while running the program iam getting bellow error.. iam giving all my config,pojo,daos please check
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'vehicleDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.orm.hibernate3.HibernateTemplate in.JavaHome.SpringHiber.DAO.vehicleDao.template; nested exception is java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
Exception in thread "main" java.lang.NoSuchMethodError: org.springframework.util.ReflectionUtils.clearCache()V
at org.springframework.context.support.AbstractApplicationContext.resetCommonCaches(AbstractApplicationContext.java:879)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:563)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at addVehicle.main(addVehicle.java:11)
Configuration spring is..
<context:component-scan base-package="in.JavaHome.SpringHiber"></context:component-scan>
<bean name="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocations" value="classpath:hibernate.cfg.xml"></property>
</bean>
<bean name="hibTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean name="hibTransManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="hibTransManager"/>
Dao Class
#Component
public class vehicleDao {
#Autowired
private HibernateTemplate template;
#Transactional
public void addVehicle(vehicle v){
template.save(v);
}
main.java
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext contex= new ClassPathXmlApplicationContext("config.xml");
vehicleDao dao = (vehicleDao) contex.getBean("vehicleDao.class");
vehicle v=new vehicle();
v.setName("S cross");
v.setCost(1500000);
dao.addVehicle(v);
}
Iam new to spring mvc so, please tell me the whr the problem.
Thank u
If my guess is correct, you are following a Tutorial to learn about Spring. If so, congratulations and good luck, Spring is a very powerful framework! Though it appears that you are using a very old tutorial - I'd suggest looking for a more modern spring tutorial example as XML configuration (as well as Hibernate 3) are not modern approach. Perhaps something from: http://spring.io/guides
but for this specific problem it seems likely that you have incompatible jars on your classpath. If you plan to use hibernate 3 you need to ensure it's on the classpath and that you are not using a modern version of spring either. See: compatability of spring 4.0.0 with hibernate 4.30
The problem is you defined bean in xml like this
<bean name="hibTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
but your using template to autowire the bean name should be same or use #Qualifier
#Autowired
private HibernateTemplate template;
change this to
#Autowired
private HibernateTemplate hibTemplate;
or
#Autowired
#Qualifier("hibTemplate")
private HibernateTemplate hibTemplate;

creating custom ItemReader with defaultLineMapper using spring annotations

I am trying to make a annotation based ItemReader in spring-batch. I was able to make the desired ItemReader in my xml but annotation based is not at all working giving the following error:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'runScheduler': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.batch.core.Job com.techavalanche.batch.RunScheduler.job; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reportJob': Cannot create inner bean '(inner bean)#3f9bb1' of type [org.springframework.batch.core.configuration.xml.SimpleFlowFactoryBean] while setting bean property 'flow'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3f9bb1': Cannot create inner bean '(inner bean)#17e6f05' of type [org.springframework.batch.core.job.flow.support.StateTransition] while setting bean property 'stateTransitions' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#17e6f05': Cannot create inner bean '(inner bean)#66da50' of type [org.springframework.batch.core.job.flow.support.state.StepState] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#66da50': Cannot resolve reference to bean 'step1' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'step1': Cannot resolve reference to bean 'customItemReader' while setting bean property 'itemReader'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customItemReader': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public org.springframework.batch.item.file.FlatFileItemReader com.techavalanche.reader.CustomReader.itemReader; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getFlatFileItemReader' defined in class path resource [com/techavalanche/reader/CustomReader.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: LineMapper is required
and it is caused by :
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.batch.core.Job com.techavalanche.batch.RunScheduler.job; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reportJob': Cannot create inner bean '(inner bean)#3f9bb1' of type [org.springframework.batch.core.configuration.xml.SimpleFlowFactoryBean] while setting bean property 'flow'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3f9bb1': Cannot create inner bean '(inner bean)#17e6f05' of type [org.springframework.batch.core.job.flow.support.StateTransition] while setting bean property 'stateTransitions' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#17e6f05': Cannot create inner bean '(inner bean)#66da50' of type [org.springframework.batch.core.job.flow.support.state.StepState] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#66da50': Cannot resolve reference to bean 'step1' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'step1': Cannot resolve reference to bean 'customItemReader' while setting bean property 'itemReader'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customItemReader': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public org.springframework.batch.item.file.FlatFileItemReader com.techavalanche.reader.CustomReader.itemReader; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getFlatFileItemReader' defined in class path resource [com/techavalanche/reader/CustomReader.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: LineMapper is required
My CustomReader is
package com.techavalanche.reader;
#Component("customReader")
public class CustomReader implements ItemReader<Report> {
#Autowired
public FlatFileItemReader<Report> itemReader;
#Bean
public FlatFileItemReader getFlatFileItemReader(){
return new FlatFileItemReader();
}
#Bean
public DefaultLineMapper getDefaultLineMapper(){
return new DefaultLineMapper();
}
#Autowired
public DefaultLineMapper<Report> lineMapper;
#Bean
public FixedLengthTokenizer getLinetokenizer(){
return new FixedLengthTokenizer();
}
#Autowired
public FixedLengthTokenizer linetokenizer;
#Bean
public BeanWrapperFieldSetMapper getBeanWrapperFieldSetMapper() {
return new BeanWrapperFieldSetMapper();
}
#Autowired
public BeanWrapperFieldSetMapper<Report> fieldSetMapper;
public Resource res=new FileSystemResource("D:\\testresource\\report.csv");
String[] names= {"date","impressions","clicks","earning"};
#Override
public Report read() throws Exception, UnexpectedInputException, ParseException,
NonTransientResourceException {
for(String name:names){
System.out.println(name);
}
linetokenizer.setNames(new String[] {"date","impressions","clicks","earning"});
Range range1=new Range(1,12);
Range range2=new Range(13,15);
Range range3=new Range(16,20);
Range range4=new Range(21,28);
Range[] ranges={range1,range2,range3,range4};
linetokenizer.setColumns(ranges);
lineMapper.setLineTokenizer(linetokenizer);
fieldSetMapper.setPrototypeBeanName("report");
lineMapper.setFieldSetMapper(fieldSetMapper);
itemReader.setResource(res);
itemReader.setLineMapper(lineMapper);
itemReader.open(new ExecutionContext());
Report report= itemReader.read();
return report;
}
}
My Xml Configuration looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
">
<context:component-scan base-package="com.techavalanche" />
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
<bean id="transactionManager"
class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
<bean id="report" class="com.techavalanche.batch.Report" scope="prototype" />
<bean id="customWriter" class="com.techavalanche.writer.CustomWriter" />
<batch:job id="reportJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="customItemReader" writer="customWriter"
commit-interval="2">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="multiResourceReader"
class=" org.springframework.batch.item.file.MultiResourceItemReader">
<property name="resources" value="file:D:\testresource\report.csv" />
<property name="delegate" ref="cvsFileItemReader" />
</bean>
<bean id="customItemReader" class="com.techavalanche.reader.CustomReader" />
<bean id="cvsFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
<!-- Read a csv file -->
<!-- <property name="resource" ref="resource" /> -->
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<!-- split it -->
<property name="lineTokenizer">
<bean id="fixedLengthLineTokenizer"
class="org.springframework.batch.item.file.transform.FixedLengthTokenizer">
<property name="names" value="date,impressions,clicks,earning" />
<property name="columns" value="1-12,13-15,16-20,21-28" />
</bean>
</property>
<property name="fieldSetMapper">
<!-- return back to reader, rather than a mapped object. -->
<!-- <bean class="org.springframework.batch.item.file.mapping.PassThroughFieldSetMapper"
/> -->
<!-- map to an object -->
<bean
class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="prototypeBeanName" value="report" />
</bean>
</property>
</bean>
</property>
</bean>
</beans>

Spring bean profile reference

I started using bean profile for conditional bean creation, but When i use the profiled bean outside of profile with ref I get exception nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'pb' is defined
<bean id="q" class="com.Q"> //spring can not create this bean since it depends on `pb` bean which is profiled.
<property name="p" ref="pb"/>
</bean>
<beans profile="a">
<bean id="pb" class="com.T"/>
</beans>
<beans profile="b">
<bean id="pb" class="com.T"/>
</beans>
How can I achieve this? I am sure a profile is on:
System.setProperty(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, "a");
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "a");

java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required in spring+hibernate

I am doing spring + hibernate apllication. When I run the application on tomcat server I am getting some exception. Below is my code.
This is my bean config file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>WEB-INF/database/db.properties</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property>
</bean>
<bean id="employeeBo" class="com.saggezza.employee.bo.impl.EmployeeBoImpl">
<property name="employeeDao" ref="employeeDao" />
</bean>
<bean id="employeeDao" class="com.saggezza.employee.dao.impl.EmployeeDaoImpl">
<constructor-arg ref="sessionFactory"></constructor-arg>
</bean>
this is my dao class.
public class EmployeeDaoImpl extends HibernateDaoSupport implements EmployeeDao {
private SessionFactory sessionFactory;
public EmployeeDaoImpl(SessionFactory sessionfactory){
this.sessionFactory=sessionfactory;
}
#Override
public List<Employee> getEmployeeDetails() {
return getHibernateTemplate().find("from Employee");
}
}
Here another class employeeBo is calling the employeeDaoImpl.
when I run thisI am getting the below exception.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeBo' defined in ServletContext resource [/WEB-INF/spring/EmployeeBean.xml]: Cannot resolve reference to bean 'employeeDao' while setting bean property 'employeeDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao' defined in ServletContext resource [/WEB-INF/spring/EmployeeBean.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
Can anybody help to resolve this. I have tried a lot and google it as well.But did get the solution.
If you have two configuration files, you duplicates 'sessionFactory' definition. Remove one of the 'sessionFactory' definitions . You would have got duplicate bean definition exception before the IllegalArgumentException.
Edit: After your comment,
public class EmployeeDaoImpl extends HibernateDaoSupport implements EmployeeDao {
public EmployeeDaoImpl(SessionFactory sessionfactory){
setSessionFactory(sessionfactory);
}
#Override
public List<Employee> getEmployeeDetails() {
return getHibernateTemplate().find("from Employee");
}
}
or get rid of constructor in above code and inject 'sessionFactory' using setter injection.See org.springframework.orm.hibernate3.support.HibernateDaoSupport.setSessionFactory(SessionFactory). I prefer later approach.
I think the problem is the type of SessionFactory you are injecting in EmployeeDaoImpl does not match with the type of the SessionFactory you used in the class.
Can you check it?
This is an old question so must be solved now but still if someone comes across this problem. Following is solution.
You can use Hibernate DAO Support by extending HibernateDAOSupport class and overriding its afterPropertiesSet() method.
This method is called in HibernateDAO support and at that time since sessionFactory is null it is throwing this error. In your custom class you can set this property explicitly and then call the same method of Parent Class (i.e. HibernateDAOSupport's addProperties() method)
package com.techcielo.spring4.hibernate.template;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
#Component("hibernateTemplate")
public class Hibernate4CustomTemplate extends HibernateTemplate{
#Autowired(required=true)
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
System.out.println("Setting SessionFactory");
this.sessionFactory = sessionFactory;
super.setSessionFactory(sessionFactory);
}
#Override
public void afterPropertiesSet() {
System.out.println("Checking if properties set..."+this.sessionFactory);
setSessionFactory(sessionFactory);
super.afterPropertiesSet();
}
}
Following can be used for sample!
I had the same problem and fix it by using Autowired constructor with EntityManagerFactory. Keyur answer is correct
#Service
class EmployeeDaoImpl #Autowired constructor(
factory: EntityManagerFactory
) : HibernateDaoSupport(), EmployeeDao {
init {
if (factory.unwrap(SessionFactory::class.java) == null) {
throw NullPointerException("factory is not a hibernate factory")
}
setSessionFactory(factory.unwrap(SessionFactory::class.java))
}
...
}

Resources