I'm getting the dreaded LazyInitializationException in my web application using Spring 3/ Hibernate 3.6 and jsp. I have OpenSessionInViewFilter in my web.xml but still it seems like my HSession is getting closed or invalidated somehow. I have also checked that there is no exception caused by my application.
Here is my web.xml
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<servlet-name>hedgebenefits</servlet-name>
</filter-mapping>
Context.xml is:
<mvc:annotation-driven/>
<tx:annotation-driven/>
<context:component-scan base-package="com.hedgebenefits.*"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/managerie"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="namingStrategy" class="org.hibernate.cfg.ImprovedNamingStrategy"/>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="packagesToScan" value="com.hedgebenefits.domain"/>
<property name="dataSource" ref="dataSource"/>
<property name="namingStrategy" ref="namingStrategy"/>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
</value>
</property>
</bean>
Jsp is:
<tr>
The list is :
<td>
<c:forEach var="admin" items="${admins}">
Admin is ${admin.username},
<c:forEach var="sector" items="${admin.sectors}">
sector is ${sector.name}
</c:forEach>
</c:forEach>
</td>
</tr>
Service is annotated with #Transactional:
#Service
#Transactional
public class AdminServiceImpl implements AdminService {
private AdminDao adminDao;
#Autowired
public AdminServiceImpl(AdminDao adminDao) {
this.adminDao = adminDao;
}
...
#Override
public List<Admin> listAllAdmins() {
return adminDao.listAllAdmins();
}
}
Dao is:
#Repository
public class AdminDaoImpl implements AdminDao{
private SessionFactory sessionFactory;
#Autowired
public AdminDaoImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
....
#Override
public List<Admin> listAllAdmins() {
List<Admin> adminList = sessionFactory.getCurrentSession().createCriteria(Admin.class)
.setMaxResults(5)
.list();
return adminList;
}
}
Edit: Added the controller and stacktrace
Controller is:
#Controller
#RequestMapping(value = "/admin")
#SessionAttributes(value = "admin")
public class AdminRegistrationController {
...
#Autowired
private AdminService adminService;
#RequestMapping(value = "/list")
public ModelAndView listRegisteredAdmins() {
List<Admin> admins = adminService.listAllAdmins();
return new ModelAndView(LIST_ADMINS.getViewName()).addObject("admins", admins);
}
Stacktrace is:
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/list.jsp at line 15
12: <td>
13: <c:forEach var="admin" items="${admins}">
14: Admin is ${admin.username},
15: <c:forEach var="sector" items="${admin.sectors}">
16: sector is ${sector.name}
17: </c:forEach>
18: </c:forEach>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:521)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:430)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:262)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1157)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:927)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:70)
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
root cause
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.hedgebenefits.domain.Admin.sectors, no session or session was closed
org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368)
org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:111)
org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:272)
org.apache.taglibs.standard.tag.common.core.ForEachSupport.toForEachIterator(ForEachSupport.java:348)
org.apache.taglibs.standard.tag.common.core.ForEachSupport.supportedTypeForEachIterator(ForEachSupport.java:224)
org.apache.taglibs.standard.tag.common.core.ForEachSupport.prepare(ForEachSupport.java:155)
javax.servlet.jsp.jstl.core.LoopTagSupport.doStartTag(LoopTagSupport.java:256)
org.apache.jsp.WEB_002dINF.jsp.list_jsp._jspx_meth_c_005fforEach_005f1(list_jsp.java:149)
org.apache.jsp.WEB_002dINF.jsp.list_jsp._jspx_meth_c_005fforEach_005f0(list_jsp.java:112)
org.apache.jsp.WEB_002dINF.jsp.list_jsp._jspService(list_jsp.java:70)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:262)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1157)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:927)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:70)
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
It seems that I'm missing something obvious here, but can't figure out what?
Related
This question already has an answer here:
What is a NoSuchBeanDefinitionException and how do I fix it?
(1 answer)
Closed 2 years ago.
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.home.dao.ProductDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
package com.home.dao;
#Repository
#Transactional
#Service
public class ProductDao implements proDaoInterface{
#Autowired
private SessionFactory sessionFactory;
public void addProduct(ProductModel product)
{
Session session= sessionFactory.getCurrentSession();
session.saveOrUpdate(product);
session.flush();
}
public ProductModel getProductByID(String ID)
{
Session session = sessionFactory.getCurrentSession();
ProductModel product = (ProductModel)session.get(ProductModel.class,ID);
session.flush();
return product;
}
#SuppressWarnings("unchecked")
public List<ProductModel> getProductList()
{
Session session= sessionFactory.getCurrentSession();
List<ProductModel> listProduct;
listProduct = session.createQuery("from ProductModel").getResultList();
session.flush();
return listProduct;
}
public void deleteProuct(String ID)
{
Session session = sessionFactory.getCurrentSession();
session.delete(getProductByID(ID));
session.flush();
}
}
controller class
#EnableWebMvc
#Controller
public class homeController {
#Autowired
private ProductDao dao;
#RequestMapping("/test")
public String home(Model model) {
List<ProductModel> productList = dao.getProductList();
model.addAttribute("productList", productList);
return "home";
}
#RequestMapping("/view/{productID}")
public String viewProduct(#PathVariable String productID, Model model) throws IOException {
ProductModel product = dao.getProductByID(productID);
model.addAttribute(product);
return "viewProduct";
}
}
Spring Configuration file
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url"
value="jdbc:oracle:thin:#localhost:1521:xe"></property>
<property name="username" value="system"></property>
<property name="password" value="admin"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hbm2ddl.auto">update</prop>
<prop key="dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="connection.pool_size">1</prop>
<prop key="show_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.home.controllers</value>
<value>com.home.dao</value>
<value>com.home.model</value>
</list>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
Dispatcher -Servlet.xml
<context:component-scan base-package="com.home.controllers"></context:component-scan>
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
<mvc:resources mapping="/images/**" location="/WEB-INF/resources/images/" />
<mvc:resources mapping="/css/**" location="/WEB-INF/resources/css/" />
<mvc:resources mapping="/fonts/**" location="/WEB-INF/resources/fonts/" />
<mvc:resources mapping="/js/**" location="/WEB-INF/resources/js/" />
<mvc:resources mapping="/view/**" location="/view/" />
<tx:annotation-driven />
</beans>
web
<display-name>Product</display-name>
<listener>
<listener-class>
*org.springframework.web.context.ContextLoaderListener*
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/ApplicationConfig.xml,
/WEB-INF/DispatcherServlet.xml
</param-value>
</context-param>
<servlet>
<servlet-name>dad-frontController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dad-frontController</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I believe your error is coming in fact you are restricting your component scan on dispatcher-servlet.xml.
Change the following:
<context:component-scan base-package="com.home.controllers"></context:component-scan>
To:
<context:component-scan base-package="com.home.*"></context:component-scan>
Checkout the official doc: https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-annotation-config
One more thing, your ProductDao has #Service and #Repository. Both say the same to Spring, so leave only #Repository.
Besides that, I would advise you to use Spring Boot, or, make those configurations via programmatically, it's way more clear =)
I've a Java Web Service with hibernate spring integration. In my project, I need to connect two same database but different locations. I need to update contents in each projects so i have configured Hibernate sessions with these databases but when i try to insert content in two databases, sessions created for one db connection another one return "org.hibernate.HibernateException: No Session found for current thread". is there any changes needed in my code? Thanks in advance.
applicationContext.xml
<context:component-scan base-package="com.sas.sakthi.rest" />
<!-- <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" /> <property name="defaultEncoding"
value="UTF-8" /> </bean> -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="dataSourceTwo" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurltwo}" p:username="${jdbc.usernametwo}"
p:password="${jdbc.passwordtwo}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.sas.sakthi.rest.model.CategoryDO</value>
<value>com.sas.sakthi.rest.model.ProductDO</value>
<value>com.sas.sakthi.rest.model.CustomerDO</value>
<value>com.sas.sakthi.rest.model.SubCategoryDO</value>
<value>com.sas.sakthi.rest.model.SmsLogDO</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="sessionFactoryTwo"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceTwo" />
<property name="annotatedClasses">
<list>
<value>com.sas.sakthi.rest.model.CategoryDO</value>
<value>com.sas.sakthi.rest.model.ProductDO</value>
<value>com.sas.sakthi.rest.model.CustomerDO</value>
<value>com.sas.sakthi.rest.model.SubCategoryDO</value>
<value>com.sas.sakthi.rest.model.SmsLogDO</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- <bean id="AbstractHibernateDAO" class="com.stnage.service.rest.dao.AbstractHibernateDAOImpl"></bean>
<bean id="BatchMessageManagerDAO" class="com.stnage.service.rest.dao.BatchMessageManagerDAOImpl"></bean>
<bean id="BatchMessageManagerService" class="com.stnage.service.rest.service.BatchMessageManagerServiceImpl"></bean> -->
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:annotation-driven transaction-manager="transactionManagerTwo" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="transactionManagerTwo"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactoryTwo" />
</bean>
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/sakthi
jdbc.username=root
jdbc.password=XXXXXX
jdbc.databaseurltwo=jdbc:mysql://192.168.2.15:3306/sakthi
jdbc.usernametwo=YYYY
jdbc.passwordtwo=XXXXXX
HibernateDAO.java
#Autowired
#Qualifier("sessionFactory")
SessionFactory sessionFactory;
#Autowired
#Qualifier("sessionFactoryTwo")
SessionFactory sessionFactoryTwo;
#Override
public void create(BaseModel entity) {
getCurrentSession().persist(entity);
}
#Override
public void update(BaseModel entity) {
getCurrentSession().merge(entity);
}
#Override
public void save(BaseModel entity) {
getCurrentSession().saveOrUpdate(entity);
}
#Override
public void delete(BaseModel entity) {
getCurrentSession().delete(entity);
}
#Override
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public void refresh(BaseModel entity) {
getCurrentSession().refresh(entity);
}
#Override
public <T> BaseModel findById(Class<T> entityClass, int entityId) {
return (BaseModel) getCurrentSession().get(entityClass, entityId);
}
#Override
public void createTwo(BaseModel entity) {
getCurrentSessionTwo().persist(entity);
}
#Override
public void updateTwo(BaseModel entity) {
getCurrentSessionTwo().merge(entity);
}
#Override
public void saveTwo(BaseModel entity) {
getCurrentSessionTwo().saveOrUpdate(entity);
}
#Override
public void deleteTwo(BaseModel entity) {
getCurrentSessionTwo().delete(entity);
}
#Override
public Session getCurrentSessionTwo() {
return sessionFactoryTwo.getCurrentSession();
}
#Override
public void refreshTwo(BaseModel entity) {
getCurrentSessionTwo().refresh(entity);
}
#Override
public <T> BaseModel findByIdTwo(Class<T> entityClass, int entityId) {
return (BaseModel) getCurrentSessionTwo().get(entityClass, entityId);
}
SmsLogDataFetchServiceImpl.java
#Service
public class SmsLogDataFetchServiceImpl implements
SmsLogDataFetchService {
#Autowired
ProductDataFetchDAO proFetchDAO;//extends HibernateDAO.java
#Override
public int savenewentry(String msg, String phoneNo, String receivedOn) {
try {
if (msg != null || phoneNo != null || receivedOn != null) {
SmsLogDO smsDO = new SmsLogDO();
smsDO.setCustomerNo(phoneNo);
smsDO.setSmsContent(msg);
smsDO.setCreatedOn(receivedOn);
smsDO.setStatus(1);
smsDO.setUpdatedOn((new Date()).toString());
proFetchDAO.save(smsDO);
proFetchDAO.saveTwo(smsDO);
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}}
In this DAO implementation class, proFetchDAO.save(smsDO) works fine but when proFetchDAO.saveTwo(smsDO) executes it returns "org.hibernate.HibernateException: No Session found for current thread".
stack traces:
Hibernate: insert into sms_log (created_by, created_on, customer_no, sms_content, status, updated_by, updated_on) values (?, ?, ?, ?, ?, ?, ?)
org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:883)
at com.sas.sakthi.rest.dao.AbstractHibernateDAOImpl.getCurrentSessionTwo(AbstractHibernateDAOImpl.java:84)
at com.sas.sakthi.rest.dao.AbstractHibernateDAOImpl.saveTwo(AbstractHibernateDAOImpl.java:74)
at com.sas.sakthi.rest.service.SmsLogDataFetchServiceImpl.savenewentry(SmsLogDataFetchServiceImpl.java:33)
at com.sas.sakthi.rest.controller.SMSGatewayReceiverController.receiveGatewaySms(SMSGatewayReceiverController.java:48)
at com.sas.sakthi.rest.controller.SMSGatewayReceiverController$$FastClassByCGLIB$$d0f8afce.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
at com.sas.sakthi.rest.controller.SMSGatewayReceiverController$$EnhancerByCGLIB$$a5284739.receiveGatewaySms(<generated>)
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 com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:540)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:715)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:205)
at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:266)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
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)
Ok, so you are using Spring's <tx:annotation-driven /> but I cannot see any of the #Transactional annotations.
Maybe you could try splitting the method for persisting entity into two separate ones, and annotating each other with #Transactional("transactionManager") and #Transactional("transactionManagerTwo").
Please read the #Transactional usage documentation.
I'm using Spring 4 Web MVC in this project. Please help me to see my configuration and the error I get below. Correct me if the way I configure is wrong. Thank you.
root-context.xml
<bean id="entityManagerFac" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" autowire="byName">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.hannacch.admin.model</value>
</list>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=DBADMIN;" />
<property name="username" value="sa" />
<property name="password" value="#dmin" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFac" />
</bean>
<tx:annotation-driven />
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<jpa:repositories base-package="com.hannacch.admin.repository" entity-manager-factory-ref="entityManagerFac"/>
servlet-context.xml
<annotation-driven />
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.hannacch.controller" />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="viewClass" value="com.hannacch.Spring.JstlView" />
<beans:property name="prefix" value="/WEB-INF/views/page/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
admin-context.xml
<annotation-driven />
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.hannacch.admin" />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="viewClass" value="com.hannacch.Spring.AdminJstlView" />
<beans:property name="prefix" value="/WEB-INF/views/admin/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
CreateUserController.java
#ModelAttribute("userCredential")
public UserCredential createModel() {
return new UserCredential();
}
#RequestMapping(method = RequestMethod.GET)
public String createUser() {
return "/admin/createUser";
}
#RequestMapping(value="/addUser", method = RequestMethod.POST)
public String doActions(#ModelAttribute UserCredential userCredential) {
userCredential.setId(1);
userCredentialService.createUserCredential(userCredential);
return "/admin/createUser";
}
createUser.jsp
<form:form action="createUser/addUser" method="POST" commandName="userCredential">
<table>
<tr>
<td><form:label path="username">Username</form:label></td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td><form:label path="password">Password</form:label></td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>adminServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/admin-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>adminServlet</servlet-name>
<url-pattern>/admin/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Previously in my servlet-context.xml and admin-context.xml, I didn't set viewClass in both xml, the model attribute was working and able to let me save data into database. After I added in viewClass in servlet-context.xml and admin-context.xml, the code is not working and I get error below:
ERROR: org.springframework.web.servlet.tags.form.LabelTag - Neither BindingResult nor plain target object for bean name 'userCredential' available as request attribute
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userCredential' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
at org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:130)
at org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:120)
at org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:90)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
at org.apache.jsp.WEB_002dINF.views.admin.createUser_jsp._jspx_meth_form_005flabel_005f0(createUser_jsp.java:224)
at org.apache.jsp.WEB_002dINF.views.admin.createUser_jsp._jspx_meth_form_005fform_005f0(createUser_jsp.java:169)
at org.apache.jsp.WEB_002dINF.views.admin.createUser_jsp._jspService(createUser_jsp.java:121)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:584)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:523)
at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:934)
at org.apache.jsp.WEB_002dINF.views.include.adminTemplate_jsp._jspService(adminTemplate_jsp.java:102)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:584)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:523)
at com.hannacch.Spring.AdminJstlView.renderMergedOutputModel(AdminJstlView.java:19)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1244)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1027)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:277)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
How can I solve this problem? What happen to my JSTLView?
AdminJSTLView.java
public class AdminJstlView extends InternalResourceView {
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
String dispatcherPath = prepareForRendering(request, response);
request.setAttribute("adminContents", dispatcherPath.substring(dispatcherPath.lastIndexOf("/") + 1));
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/views/include/adminTemplate.jsp");
requestDispatcher.include(request, response);
}
}
The error occured because of missing to expose the model object while overriding renderMergedOutputModel.
#Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
exposeModelAsRequestAttributes(model, request);
String dispatcherPath = prepareForRendering(request, response);
request.setAttribute("adminContents", dispatcherPath.substring(dispatcherPath.lastIndexOf("/") + 1));
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/views/include/adminTemplate.jsp");
requestDispatcher.include(request, response);
}
I am trying to implement log in authentication using spring security userDeatilsService and I have tried the following things so far,
userdetailsService:
#Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private UserDao userDao;
#Override
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
User user=userDao.findUserByName(username);
if(user!=null)
{
String password=user.getPassowrd();
boolean enabled=user.getStatus().equals(UserStatus.ACTIVE);
boolean accountNonExpired = user.getStatus().equals(UserStatus.ACTIVE);
boolean credentialsNonExpired = user.getStatus().equals(UserStatus.ACTIVE);
boolean accountNonLocked = user.getStatus().equals(UserStatus.ACTIVE);
//populate user roles
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for(Role role : user.getRoles()){
authorities.add(new GrantedAuthorityImpl(role.getRoleName()));
}
//create spring security object
org.springframework.security.core.userdetails.User securityUser = new
org.springframework.security.core.userdetails.User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
return securityUser;
}else {
throw new UsernameNotFoundException("user not found !!!");
}
-servlet.xml:
<context:component-scan base-package="com.dz.hrportal.controller" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="cacheSeconds" value="0"/>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<mvc:resources mapping="/resources/**" location="/CSS/" />
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/portal"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="org.assessme.com.controller.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
Web.xml:
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml,/WEB-INF/spring-security.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
-security.xml:
<security:http>
<security:intercept-url pattern="/admin**" access="ROLE_USER" />
<security:form-login login-page="/login"
default-target-url="/admin"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<security:logout logout-success-url="/logout" />
</security:http>
<bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService"></property>
</bean>
<bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<list>
<ref local="daoAuthenticationProvider"/>
</list>
</property>
</bean>
<bean id="userDetailsService" class="com.dz.hrportal.service.UserDetailsServiceImpl"></bean>
<security:authentication-manager>
<security:authentication-provider user-service-ref="userDetailsService">
<security:password-encoder hash="md5"></security:password-encoder>
</security:authentication-provider>
</security:authentication-manager>
<context:annotation-config />
<context:component-scan base-package="com.dz.hrportal.dao,com.dz.hrportal.dao.impl,com.dz.hrportal.service" />
and I am getting the following errors:
complete stack trace:
UPDATE:
UserDao:
public interface UserDao {
void addUser(User user);
void editUser(User user);
void deleteUser(int userId);
User findUser(int userId);
User findUserByName(String username);
List<User> getAllUsers();
}
and UserDaoImple;
#Repository
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory session;
#Override
public void addUser(User user) {
session.getCurrentSession().save(user);
}
#Override
public void editUser(User user) {
session.getCurrentSession().update(user);
}
#Override
public void deleteUser(int UserId) {
session.getCurrentSession().delete(findUser(UserId));
}
#Override
public User findUser(int userId) {
return (User) session.getCurrentSession().get(User.class,userId);
}
#Override
public User findUserByName(String username) {
Criteria criteria=session.getCurrentSession().createCriteria(User.class);
criteria.add(Restrictions.eq("username", username));
return (User) criteria.uniqueResult();
}
#Override
public List<User> getAllUsers() {
return session.getCurrentSession().createQuery("from User").list();
}
Stack trace:
17:26:09,810 DEBUG DefaultListableBeanFactory:334 - Ignoring bean class loading failure for bean 'sessionFactory'
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate4.LocalSessionFactoryBean] for bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate4.LocalSessionFactoryBean
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1254)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:576)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1323)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:315)
at org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:185)
at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:73)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:100)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:86)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:68)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:359)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1426)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.initMessageSource(AbstractApplicationContext.java:773)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:377)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:278)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4350)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.ClassNotFoundException: org.springframework.orm.hibernate4.LocalSessionFactoryBean
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1360)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1206)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:257)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408)
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1275)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1246)
... 38 more
17:26:09,814 DEBUG DefaultListableBeanFactory:334 - Ignoring bean class loading failure for bean 'transactionManager'
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate4.HibernateTransactionManager] for bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate4.HibernateTransactionManager
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1254)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:576)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1323)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:315)
at org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:185)
at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:73)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:100)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:86)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:68)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:359)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1426)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.initMessageSource(AbstractApplicationContext.java:773)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:377)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:278)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4350)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.ClassNotFoundException: org.springframework.orm.hibernate4.HibernateTransactionManager
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1360)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1206)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:257)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408)
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1275)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1246)
I solved the bug. Actually the org.springframework.transaction-3.1.RELEASE.jar was missing so,added and now it seems working.
add this dependency :
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
Spring is not able to create bean for
com.dz.hrportal.dao.UserDao why because you did not specify the package of UserDao class in <context:component-scan base-package="com.hrportal.controller" />, since you have given com.hrportal.controller spring will create beans only for the classes inside that package and will not create beans for the classes inside package com.dz.hrportal.dao.UserDao. change this tag to <context:component-scan base-package="com.hrportal" />. Hope this helps
I haven't use spring much, but judge from the stack trace, spring cannot find userDao's implementation.
Have you specify the implement bean for userDao, or use auto component scan for the correct java package?
I am using springframework 3.2 with jboss server 7.1 .
Trying to set up a simple spring app with jpa2(hibernate provider, mysql) and spring mvc.
I use a simple DAO which i inject with autowired annotation in the home controller.
This dao class simply has a field (em) for persistentContext to get injected, it coudlnt be more trivial, i dont use a persistence.xml since spring from version 3.1 and up does not need one.....note that packages are scanned properly
i have tried everything from other solutions posted in the web (including here)...
but i get this error:
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: com.stko.home.model.daos.UserDao
com.stko.home.controllers.HomeController.userDao; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'userDao': Injection of persistence
dependencies failed; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
unique bean of type [javax.persistence.EntityManagerFactory] is
defined: expected single bean but found 0:
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1120)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:598)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:517)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:458)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
javax.servlet.GenericServlet.init(GenericServlet.java:242)
org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50)
org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930)
java.lang.Thread.run(Thread.java:722)
my applicationContext.xml:
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mmydb"/>
<property name="username" value="user"/>
<property name="password" value="1234"/>
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="com.stko.home.model.entities"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.show.sql">true</prop>
<prop key="hibernate.connection.charSet"> UTF-8</prop>
</props>
</property>
</bean>
<!-- tell spring to use annotation based congfigurations -->
<context:annotation-config />
<!-- scan for beans -->
<context:component-scan base-package="com.stko.home.model.daos"/>
<!-- to recognize persistnce annotations like PersistenceContext -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="databaseProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:database.properties"/>
</bean>
my servlet-context.xml:
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.stko.home"/>
my web.xml:
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
my userDao:
#Service("userDao")
#Repository
public class UserDao implements Serializable {
#PersistenceContext
private EntityManager em;
#Transactional
public void saveUser(User user) {
if(user!=null)
em.persist(user);
}
}
my entity class User:
#Entity
#Table(name = "user")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "userid")
private Integer userid;
#Column(name="username")
private String username;
public User(){}
}
my typical home controller:
#Controller
public class HomeController {
.....
#Autowired
UserDao userDao;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
.....
User newUser = new User();
newUser.setName("blabla");
userDao.saveUser(newUser);
return "home";
}
}
Do you have a persistence.xml in which you have defined your persistence unit?
The issue most likely is this line in servlet-context.xml file:
<context:component-scan base-package="com.stko.home"/>
which is essentially trying to create your DAO once more in your Web application Context. You should just have a filter which only creates your controllers here, this way:
<context:component-scan base-package="com.stko.home">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation" />
</context:component-scan>
Try this
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
Define the properties for your EMF bean, persistenceUnit should be the name you declare on persistence.xml