Images of All Jars
This is the error image from the console.
I am trying to use the Jersey API along with Spring and Hibernate. However, defining session factory says NullPointerException. Can anybody help me to solve this? Added Full configuration with spring, hibernate and Jersey. Images of error and jar on top.
---------------------Dao Class:
package com.org.restservice.bo.user;
import java.util.List;
import com.org.restservice.common.Dao;
public interface AuthenticationDao extends Dao{
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception;
}
---------------------DaoHibernate Class:
package com.org.restservice.bo.user;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.type.StringType;
import org.springframework.orm.hibernate3.HibernateCallback;
import com.org.restservice.common.BaseDaoHibernate;
import com.org.restservice.common.Constant;
public class AuthenticationDaoHibernate extends BaseDaoHibernate implements AuthenticationDao{
private Log log = LogFactory.getLog(AuthenticationDaoHibernate.class);
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception{
System.out.println("Called Me>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
List<AuthenticationVo> findlist = new ArrayList<AuthenticationVo>();
final String sqlQuery = "SELECT USER_ID, ROLE_ID from STTM_USER_MASTER";
System.out.println("sqlQuery: "+sqlQuery);
List results = (List) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
SQLQuery sq = session.createSQLQuery(sqlQuery);
sq.addScalar("USER_ID", StringType.INSTANCE);
sq.addScalar("ROLE_ID", StringType.INSTANCE);
return sq.list();
}
});
try {
if (results.size() > 0) {
Iterator itr = results.iterator();
while (itr.hasNext()) {
authenticationVo = new AuthenticationVo();
Object[] row = (Object[]) itr.next();
authenticationVo.setUser_id((String) row[0]);
authenticationVo.setRole_id((String) row[1]);
findlist.add(authenticationVo);
}
}
} catch (Exception e) {
System.out.println("FunctonVos error:" + e.getMessage());
}
System.out.println("Size of User List is: "
+ findlist.size());
System.out.println("Procedure call ended.");
return findlist;
}
}
---------------------Facade Class:
package com.org.restservice.bo.user;
import java.util.List;
import com.org.restservice.common.Facade;
public interface AuthenticationFacade extends Facade{
public void setAuthenticationDao(AuthenticationDao authenticationDao);
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception;
}
---------------------FacadeImpl Class:
package com.org.restservice.bo.user;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.org.restservice.common.BaseFacade;
public class AuthenticationFacadeImpl extends BaseFacade implements AuthenticationFacade{
private static final Log log = LogFactory.getLog(AuthenticationFacadeImpl.class);
private AuthenticationDao authenticationDao;
public void setAuthenticationDao(AuthenticationDao authenticationDao) {
this.authenticationDao = authenticationDao;
}
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception{
return authenticationDao.userInfo(authenticationVo);
}
}
---------------------Business Object Class:
package com.org.restservice.bo.user;
import com.org.restservice.common.BaseObject;
public class AuthenticationVo extends BaseObject{
private static final long serialVersionUID = 1L;
private String user_id;
private String role_id;
public AuthenticationVo(String user_id, String role_id) {
super();
this.user_id = user_id;
this.role_id = role_id;
}
public AuthenticationVo() {
super();
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getRole_id() {
return role_id;
}
public void setRole_id(String role_id) {
this.role_id = role_id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((role_id == null) ? 0 : role_id.hashCode());
result = prime * result + ((user_id == null) ? 0 : user_id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AuthenticationVo other = (AuthenticationVo) obj;
if (role_id == null) {
if (other.role_id != null)
return false;
} else if (!role_id.equals(other.role_id))
return false;
if (user_id == null) {
if (other.user_id != null)
return false;
} else if (!user_id.equals(other.user_id))
return false;
return true;
}
#Override
public String toString() {
return "AuthenticationVo [user_id=" + user_id + ", role_id=" + role_id + "]";
}
}
---------------------Action Class Declaration:
package com.org.restservice.portal.user;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.org.restservice.bo.user.AuthenticationFacade;
import com.org.restservice.bo.user.AuthenticationVo;
#Path("userService")
public class UserAction{
private final Log log = LogFactory.getLog(UserAction.class);
AuthenticationVo authenticationVo = new AuthenticationVo();
private AuthenticationFacade authenticationFacade = null;
private List<AuthenticationVo> listofUsers = new ArrayList<AuthenticationVo>();
public AuthenticationVo getAuthenticationVo() {
return authenticationVo;
}
public void setAuthenticationVo(AuthenticationVo authenticationVo) {
this.authenticationVo = authenticationVo;
}
public AuthenticationFacade getAuthenticationFacade() {
return authenticationFacade;
}
public void setAuthenticationFacade(AuthenticationFacade authenticationFacade) {
this.authenticationFacade = authenticationFacade;
}
public List<AuthenticationVo> getListofUsers() {
return listofUsers;
}
public void setListofUsers(List<AuthenticationVo> listofUsers) {
this.listofUsers = listofUsers;
}
#GET
#Produces( "application/json" )
public List<AuthenticationVo> customAction(){
if (log.isDebugEnabled()) {
log.debug("Entering into loadusers Method of AuthenticationAction: " +authenticationFacade);
}
try {
listofUsers = authenticationFacade.userInfo(authenticationVo);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(">>>>>>>>>>>>>>>>>>>>>" +listofUsers.size());
/*authenticationVo.setUser_id("1234");
authenticationVo.setRole_id("134352");
listofUsers.add(authenticationVo);*/
return listofUsers;
}
}
---------------------Spring Beans Declaration:
<!-- <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.xsd"> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Database connection using jndi properties-->
<import resource="config/applicationContext-jndi.xml"/>
<import resource="config/applicationContext.xml"/>
<!-- List and Setup -->
<import resource="config/applicationContext-auth.xml"/>
</beans>
---------------------Application Context Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</prop>
</props>
</property>
</bean>
<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- Transaction template for Facade -->
<bean id="txProxyTemplate" abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<!-- DAO bean -->
<!-- Generic DAO - can be used when doing standard CRUD -->
<bean id="dao" class="com.org.restservice.common.BaseDaoHibernate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Generic Facade that can be used to do basic CRUD operations on any
objects -->
<bean id="facade" parent="txProxyTemplate">
<property name="target">
<bean class="com.org.restservice.common.BaseFacade">
<property name="Dao" ref="dao" />
</bean>
</property>
</bean>
</beans>
--------------------- Context Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- Transaction declarations for business services. -->
<bean id="authenticationFacade" parent="txProxyTemplate">
<property name="target">
<bean
class="com.org.restservice.bo.user.AuthenticationFacadeImpl">
<property name="authenticationDao">
<ref bean="authenticationDao" />
</property>
</bean>
</property>
</bean>
<!-- authenticationDao: Hibernate implementation -->
<bean id="authenticationDao"
class="com.org.restservice.bo.user.AuthenticationDaoHibernate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
</beans>
---------------------Jndi Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<!-- author: Sarkar Zahir Ahamed <ahamed.sarkar#dbbl.com.bd> -->
<beans>
<!-- ========================= PERSISTENCE DEFINITIONS ========================= -->
<!-- JNDI DataSource for J2EE environments -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:/comp/env/jndi/orcl</value>
</property>
</bean>
</beans>
---------------------Web XML Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>RestWebService</display-name>
<!-- Spring Listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Jersey Servlet -->
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers -->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.org.restservice</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<!-- loading Spring Context for registering beans with ApplicationContext -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/classes/SpringBeans.xml</param-value>
</context-param>
<!-- welcome file -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Related
I am getting error :
java.lang.ClassNotFoundException:
org.springframework.web.servlet.handler.SimpleMappingExceptionResolver
I am hitting URL : http://localhost:8080/SpringMvcExceptionHandling/student on my local machine
Full Strack Trace is :
I have already checked most of the question/answer but not getting any help to resolve my issue,Please help.
Here is what I have done :
I am working on Spring Exception Handling with Jars(Spring-3.1.2). I am not using maven.
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>SpringMvcExceptionHandling</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMvcExceptionHandling</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringMvcExceptionHandling-servlet.xml 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" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:component-scan base-package="com.exceptionhandling.mvc.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.handler.
SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.exceptionhandling.mvc.controller.SpringException">
ExceptionPage
</prop>
<prop key="java.lang.Exception">error</prop>
</props>
</property>
<property name="defaultErrorView" value="/error" />
</bean>
</beans>
StudentController.java
package com.exceptionhandling.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.exceptionhandling.mvc.model.Student;
#Controller
public class StudentController {
#RequestMapping(value = "/student")
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
#ExceptionHandler({SpringException.class})
public String addStudent(#ModelAttribute("SpringMvcExceptionHandling") Student student,
ModelMap model) {
if (student.getName().length() < 5) {
throw new SpringException("Given name is too short");
} else {
model.addAttribute("name", student.getName());
}
if (student.getAge() < 10) {
throw new SpringException("Given age is too low");
} else {
model.addAttribute("age", student.getAge());
}
model.addAttribute("id", student.getId());
return "result";
}
}
SpringException.java
package com.exceptionhandling.mvc.controller;
public class SpringException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String exceptionMsg;
public SpringException(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
public String getExceptionMsg() {
return exceptionMsg;
}
public void setExceptionMsg(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
}
My Project Structure Looks Like
Jars
Added Two External Jars :
In your SpringMvcExceptionHandling-servlet.xml file, your bean class name must be fully qualified (with no spaces in between).
So your solution must be:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
I have following xml configuration in my spring context xml, I have used annotation based approach very less and unable to figure out how to represent following using annotation, need help.
<bean id="myPolicyAdmin" class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
<constructor-arg>
<bean class="org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails">
<property name="accessTokenUri" value="${accessTokenEndpointUrl}" />
<property name="clientId" value="${clientId}" />
<property name="clientSecret" value="${clientSecret}" />
<property name="username" value="${policyAdminUserName}" />
<property name="password" value="${policyAdminUserPassword}" />
</bean>
</constructor-arg>
</bean>
In my java class(Policy manager) it is referred as following, I am actually referring a sample and trying to convert it all annotation baesed.
#Autowired
#Qualifier("myPolicyAdmin")
private OAuth2RestTemplate myPolicyAdminTemplate;
EDIT:
I tried creating a bean for org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails but not sure how to set its properties and how to access it as constructor args to myPolicyAdminTemplate
You can configure the same beans using JavaConfig as follows:
#Component
#Configuration
public class AppConfig
{
#Value("${accessTokenEndpointUrl}") String accessTokenUri;
#Value("${clientId}") String clientId;
#Value("${clientSecret}") String clientSecret;
#Value("${policyAdminUserName}") String username;
#Value("${policyAdminUserPassword}") String password;
#Bean
public OAuth2RestTemplate myPolicyAdmin(ResourceOwnerPasswordResourceDetails details)
{
return new OAuth2RestTemplate(details);
}
#Bean
public ResourceOwnerPasswordResourceDetails resourceOwnerPasswordResourceDetails()
{
ResourceOwnerPasswordResourceDetails bean = new ResourceOwnerPasswordResourceDetails();
bean.setAccessTokenUri(accessTokenUri);
bean.setClientId(clientId);
bean.setClientSecret(clientSecret);
bean.setUsername(username);
bean.setPassword(password);
return bean;
}
}
To set the props of a bean you can either use #Value during construction:
How to inject a value to bean constructor using annotations
and this one:
Spring: constructor injection of primitive values (properties) with annotation based configuration
Or #Value in the variables. You could also actually use #Resource, but I wouldn't recommend it.
In your case, the constructor for the
org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails
Would be kinda like
#Autowired
public ResourceOwnerPasswordResourceDetails(
#Value("${accessTokenEndpointUrl}") String accessTokenUri,
#Value("${clientId}") String clientId,
#Value("${clientSecret}") String clientSecret,
#Value("${policyAdminUserName}") String username,
#Value("${policyAdminUserPassword}") String password
)
I shall give you a XML configuration with it anotation based config equivalent respectively, so that you will easily see how to change your bean from xml to java and vice-versa
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.mycompany.backendhibernatejpa.controller" />
<mvc:annotation-driven />
<bean id="iAbonneDao" class="com.mycompany.backendhibernatejpa.daoImpl.AbonneDaoImpl"/>
<bean id="iAbonneService" class="com.mycompany.backendhibernatejpa.serviceImpl.AbonneServiceImpl"/>
<!-- couche de persistance JPA -->
<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 name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:bd.properties"/>
</bean>
<!-- la source de donnéees DBCP -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
<property name="driverClassName" value="${bd.driver}" />
<property name="url" value="${bd.url}" />
<property name="username" value="${bd.username}" />
<property name="password" value="${bd.password}" />
</bean>
<!-- le gestionnaire de transactions -->
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- traduction des exceptions -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<!-- annotations de persistance -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans>
this file is named springrest-sevlet. actually you can give the name you want followed by "-servlet" and mention that name in the file web.xml
<web-app>
<display-name>Gescable</display-name>
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
the two files should be place in the folder "WEB-INF".
Now the equivalent with anotation based config
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.backendhibernatejpaannotation.configuration;
import com.mycompany.backendhibernatejpaannotation.daoImpl.AbonneDaoImpl;
import com.mycompany.backendhibernatejpaannotation.daoInterface.IAbonneDao;
import com.mycompany.backendhibernatejpaannotation.serviceImpl.AbonneServiceImpl;
import com.mycompany.backendhibernatejpaannotation.serviceInterface.IAbonneService;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
*
* #author vivien saa
*/
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.mycompany.backendhibernatejpaannotation")
public class RestConfiguration {
#Bean
public IAbonneDao iAbonneDao() {
return new AbonneDaoImpl();
}
#Bean
public IAbonneService iAbonneService() {
return new AbonneServiceImpl();
}
// #Bean
// public PropertyPlaceholderConfigurer placeholderConfigurer() {
// PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
// placeholderConfigurer.setLocations("classpath:bd.properties");
// return placeholderConfigurer;
// }
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/gescable");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
#Bean
public HibernateJpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
return jpaVendorAdapter;
}
#Bean
public InstrumentationLoadTimeWeaver loadTimeWeaver() {
InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
return loadTimeWeaver;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource());
entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
entityManagerFactory.setLoadTimeWeaver(loadTimeWeaver());
return entityManagerFactory;
}
#Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return jpaTransactionManager;
}
#Bean
public PersistenceExceptionTranslationPostPro`enter code here`cessor persistenceExceptionTranslationPostProcessor() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() {
return new PersistenceAnnotationBeanPostProcessor();
}
}
this file must be accompanied by this one
package com.mycompany.backendhibernatejpaannotation.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
*
* #author vivien saa
*/
public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RestConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
I've been currently working on a Maven + Spring + Hibernate project. Actually, this is just a test project just to get familiar on how Spring works with Hibernate (+Maven). I've already setup and prepare the necessary dependencies. i.e. the appcontext.xml for Spring, the persistence.xml for Hibernate, the entity and DAO objects for JPA/Persistence/Hibernate.
During debug, persist method throws Transactionrequiredexception, no transaction in progress. I don't know what's causing this
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-datasource.xml
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<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/applicationContext-servlet.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>
</web-app>
application-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<context:component-scan base-package="com.names.home" />
<!-- Default locale set -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
<!-- Tell Spring to not try to map things in these directories to controllers -->
<!-- Order must be set to supercede the handler configured by the mvc:annotation-driven annotation -->
<mvc:resources order="-10" location="/img/" mapping="/img/**" />
<mvc:resources order="-10" location="/css/" mapping="/css/**" />
<mvc:resources order="-10" location="/js/" mapping="/js/**" />
<mvc:resources order="-10" location="/fonts/" mapping="/fonts/**" />
<mvc:resources order="-10" location="favicon.ico" mapping="favicon.ico" />
<mvc:resources order="-10" location="robots.txt" mapping="robots.txt" />
</beans>
applicationContext-datasource.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- The "webDS" data source is the main data source for names. It is referenced and
should be configured via JNDI in your particular environment. -->
<jee:jndi-lookup id="datasource" jndi-name="jdbc/web"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven transaction-manager="transactionManager" />
<context:annotation-config/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory" >
<property name="persistenceUnitName" value="wzpu"/>
<property name="dataSource" ref="datasource" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
admincontroller.java
package com.names.home;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class AdminController {
#Resource(name="profiledao")
protected ProfileDao profiledao;
#RequestMapping(value="/admin/insert")
#Transactional
public String insert(){
Profile pr = new Profile();
pr.setId(1);
profiledao.save(pr);
return "home";
}
}
ProfileDao.java
package com.names.home;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
#Repository
public class ProfileDao {
#PersistenceContext(unitName = "wzpu")
protected EntityManager em;
public Profile find(){
return this.em.find(Profile.class, 2);
}
public void save(Profile profile){
this.em.persist(profile);
em.flush();
}
}
Profile.java
package com.names.home;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "profile")
public class Profile implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name = "PROFILE_ID",nullable=false,unique=true)
protected int id;
public Profile() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Profile other = (Profile) obj;
if (id != other.id)
return false;
return true;
}
}
Please help me resolving this
The root of your issue is that the bean you've annotated with the #Transactional annotation is not being picked up by the context that contains the tx:annotation-driven post processor. You have a couple options. Move the #Transactional to a bean that is loaded by the context that contains the tx:annotation-driven post processor or move the tx:annotation-driven post processor into the same context that the #Transactional bean is being loaded.
The answer here is a similar situation.
All - In the Spring 3.0, in the applicationContext.xml .... are we supposed to have the bean property name and the reference value to be the same ? If I give a different value, it returns null object. But on giving the same value, it works. For my project, i am supposed to give different values for them. Kindly help. bye, HS
This works: (same values)
<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction">
<property name="cacheDelegate">
<ref bean="cacheDelegate" />
</property>
</bean>
This doesn't work: (different values)
<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction">
<property name="cacheDelegate">
<ref bean="MNCCacheDelegate" />
</property>
</bean>
bye, HS
My Full Code here:
WIRAdminBaseAction.java ---> my base action
AuthenticateAction.java ---> my java file that calls the bean here
applicationContext.xml --> system's applicationcontext file
applicationContext_MNC.xml ---> my applicationContext for a specific company ... this is getting loaded by my java file, which gets invoked by the web.xml file.
CacheDelegate.java
StatusDBDAO.java
PreXMLWebApplicationContext.java ----> loads my applicationContext file for the specific company.
****** applicationContext.xml ******
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<bean name="exceptionHandler" class="com.megasoft.wir.eStatement.web.interceptor.WIRExceptionHandlerInterceptor"/>
<bean name="security" class="com.megasoft.wir.eStatement.web.interceptor.SecurityInterceptor"/>
<bean name="permission" class="com.megasoft.wir.eStatement.web.interceptor.PermissionInterceptor"/>
<!-- AutoProxies -->
<bean name="loggingAutoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="interceptorNames">
<list>
<value>base</value>
<value>exceptionHandler</value>
<value>security</value>
<value>permission</value>
</list>
</property>
</bean>
</beans>
****** applicationContext_MNC.xml ******
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction">
<property name="cacheDelegate">
<ref bean="MNCCacheDelegate" />
</property>
</bean>
<bean id="MNCCacheDelegate" class="com.megasoft.wiradmin.delegate.CacheDelegate" >
<property name="statusDBDAO"><ref bean="MNCStatusDBDAO" /></property>
</bean>
<bean id="MNCStatusDBDAO" class="com.megasoft.wiradmin.dao.StatusDBDAO">
<property name="dataSource">
<ref bean="MNCAdminDataSource" />
</property>
</bean>
<!-- database configuration from property file -->
<bean id="MNCAdminDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close" lazy-init="default" autowire="default" dependency-check="default">
<property name="driverClass" value="${jdbc.driver}" ></property>
<property name="jdbcUrl" value="${admin.jdbc.url}" ></property>
<property name="user" value="${admin.jdbc.user}" ></property>
<property name="password" value="${admin.jdbc.password}" ></property>
<property name="initialPoolSize" value="3" ></property>
<property name="minPoolSize" value="3" ></property>
<property name="maxPoolSize" value="25" ></property>
<property name="acquireIncrement" value="1" ></property>
<property name="acquireRetryDelay" value="1000" ></property>
<property name="debugUnreturnedConnectionStackTraces" value="true" ></property>
<property name="maxIdleTime" value="300" ></property>
<property name="unreturnedConnectionTimeout" value="300000" ></property>
<property name="preferredTestQuery" value="SELECT COUNT(*) FROM LOCALE_CODE" ></property>
<property name="checkoutTimeout" value="300000" ></property>
<property name="idleConnectionTestPeriod" value="600000" ></property>
</bean>
<!-- this bean is set to map the constants which needs to be configured as per
the environment to the java constants file -->
<bean id="envConstantsConfigbean" class="com.megasoft.wiradmin.util.constants.Environm entConstantsSetter">
<property name="loginUrl" value="${login.url}"/>
<property name="logoutIR" value="${logout.from.image.retrieval}"/>
<property name="adminModuleUrl" value="${admin.url}"/>
<property name="adminUrlSym" value="${admin.url.sym}"/>
<property name="envProperty" value="${env.property}"/>
</bean>
</beans>
****** AuthenticateAction.java ******
package com.megasoft.wiradmin.web.action;
import java.net.UnknownHostException;
import java.sql.SQLException;
import org.bouncycastle.crypto.CryptoException;
import org.springframework.context.ApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.web.context.support.WebApplica tionContextUtils;
import com.megasoft.wiradmin.delegate.ICacheDelegate;
public class AuthenticateAction extends WIRAdminBaseAction {
private static final long serialVersionUID = 1L;
public String authenticate() throws UnknownHostException, CryptoException,
DataAccessException, SQLException{
/** This way of calling works...... This is not encouraged, as we should not use applicationContext always **/
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContex t(getServletRequest().getSession().getServletConte xt());
ICacheDelegate cacheAction = (ICacheDelegate) applicationContext.getBean("MNCCacheDelegate");
/** The below way of calling does NOT work .... returns null value.... Please help...
* I assume that, since I have extended the WIRAdminBaseAction, i should be able to call the getCacheDelegate directly
* and it should return my cacheDelegate object ...
* Again, Please note.....if I change my applicationContext_MNC.xml as below, the below way of calling works fine...
* but, i don't want to change my applicationContext_MNC.xml as below, due to some necessity.
*
<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction">
<property name="cacheDelegate">
<ref bean="cacheDelegate" />
</property>
</bean>
*
<bean id="cacheDelegate" class="com.megasoft.wiradmin.delegate.CacheDelegate" >
<property name="statusDBDAO"><ref bean="MNCStatusDBDAO" /></property>
</bean>
*
... is it that the name and bean should have the same value.... ??? No Need to be.....Am i right ? Please advise.
*
* **/
getCacheDelegate().getActorAction(1); // this way of calling doesn't work and returns null value. please help.
return "success";
}
}
****** WIRAdminBaseAction.java ******
package com.megasoft.wiradmin.web.action;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.config.entities.Parameteri zable;
import com.megasoft.wiradmin.delegate.ICacheDelegate;
public class WIRAdminBaseAction extends ActionSupport implements Preparable, ParameterAware, Parameterizable, SessionAware,RequestAware {
private HttpServletRequest request;
private static final long serialVersionUID = 1L;
private HttpServletResponse response;
private ICacheDelegate cacheDelegate;
private Map session;
private Map<String, String> params;
private Map parameters;
public void prepare() throws Exception {
}
public String execute() throws Exception {
return SUCCESS;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletRequest getServletRequest() {
return this.request;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public HttpServletResponse getServletResponse() {
return this.response;
}
public ICacheDelegate getCacheDelegate() {
return cacheDelegate;
}
public void setCacheDelegate(ICacheDelegate cacheDelegate) {
this.cacheDelegate = cacheDelegate;
}
public void addParam(final String key, final String value) {
this.params.put(key, value);
}
public Map getParams() {
return params;
}
public void setParams(final Map<String, String> params) {
this.params = params;
}
public Map getSession() {
return this.session;
}
public void setSession(final Map session) {
this.session = session;
}
public void setParameters(final Map param) {
this.parameters = param;
}
}
PreXMLWebApplicationContext.java **
package com.megasoft.wiradmin.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.support.XmlWebApplicationContext;
public class PreXMLWebApplicationContext extends XmlWebApplicationContext {
/**
* This initializes the Logger.
*/
private static Log logger = LogFactory.getLog(PreXMLWebApplicationContext.class);
protected String[] getDefaultConfigLocations() {
String environment = System.getProperty("envProperty");
String webirConfig = System.getProperty("webirConfig");
String fi = System.getProperty("FI");
String preHostConfiguration =null;
logger.info("The environment is "+environment);
logger.info("The webirConfig is "+webirConfig);
logger.info("The fi is "+fi);
if(environment != null && webirConfig != null && fi != null) {
preHostConfiguration = DEFAULT_CONFIG_LOCATION_PREFIX +
"classes/applicationContext" + "_" + fi.toUpperCase() +
DEFAULT_CONFIG_LOCATION_SUFFIX;
}
return new String[]{DEFAULT_CONFIG_LOCATION, preHostConfiguration};
}
/**
* This is close API.
*
* #see org.springframework.context.support.AbstractApplicationContext
* #close()
*/
public void close() {
this.doClose();
logger.info("Login-->into the closed");
}
}
<property name="userDelegate" ref="userDelegate" />
name is the field name in your class. When name is userDelegate, it means that WIRAdminBaseAction has a field named userDelegate (and probably a setter setUserDelegate())
ref is the bean name you want to set this field to. In your example, you should have another bean, named userDelegate or bmoUserDelegate which should be set as userDelegate in WIRAdminBaseAction.
So if you want to use the second configuration:
You just need to create a bean with id bmoUserDelegate:
<bean id="bmoUserDelegate" class="mypackage.BmoUserDelegateClass"/>
I am getting an error while accessing the web page. here is my code -
web.xml file -
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
dispatcher servlet with name - "dispatcher-servlet.xml"
<context:annotation-config />
<context:component-scan base-package="com.webProject.controller"></context:component-scan>
<!-- <context:component-scan base-package="com.webProject">
<context:include-filter type="aspectj" expression="com.webProject.*" />
</context:component-scan>
-->
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="mysqlDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/school" />
<property name="username" value="root" />
<property name="password" value="test" />
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="mysqlDataSource" />
<property name="annotatedClasses">
<list>
<value>com.webProject.model.Student</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="javax.persistence.validation.mode">none</prop>
<prop key="connection.autocommit">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
<!-- <bean id="studentDao" class="com.webProject.dao.StudentDaoImpl"></bean>-->
</beans>
Student controller class -
package com.webProject.controller;
#Controller
#RequestMapping("/Student")
public class StudentController {
#Autowired
private IStudentDao studentDao;
//List<Student> students;
/*public StudentController() {
students = new ArrayList<Student>();
}*/
public IStudentDao getStudentDao() {
return studentDao;
}
public void setStudentDao(IStudentDao studentDao) {
this.studentDao = studentDao;
}
#RequestMapping(value="details/{number}",method=RequestMethod.GET)
public String studentDetails(#PathVariable("number") int studentNumber, Model model){
//Student student = this.students.get(studentNumber);
Student student = (Student) getStudentDao().load(new Long(studentNumber));
model.addAttribute("student",student);
model.addAttribute("studentNumber", Integer.toString(studentNumber));
return "studentDetails";
}
#RequestMapping(value="addStudent", method=RequestMethod.POST)
public String addStudent(#ModelAttribute("student") Student student, Model model){
if(student != null){
getStudentDao().save(student);
//this.students.add(student);
model.addAttribute("student", student);
model.addAttribute("studentNumber", Integer.toString(getStudentDao().count()));
return "studentAddSuccess";
}else{
throw new NullPointerException();
}
}
#RequestMapping(value="studentRegistration")
public String sendStudentForm(Model model){
Student student = new Student();
model.addAttribute("student", student);
return "studentForm";
}
#RequestMapping(value="delete/{studentNumber}")
public String deleteStudent(#PathVariable("studentNumber") int studentNumber, Model model){
Student student = (Student) getStudentDao().load(new Long(studentNumber));
model.addAttribute("std", student);
getStudentDao().deleteById(new Long(studentNumber));
return "deleteStudent";
}
}
studentform.jsp
<body>
<form:form method="post" modelAttribute="student" action="addStudent">
<table>
<tr>
<td>Student Name</td>
<td>form:input path="studentName"</td>
</tr>
<tr>
<td>Department</td>
<td>form:input path="department"</td>
</tr>
<tr>
<td>College</td>
<td>form:input path="collegeName"</td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
</body>
when i mention -
this i get an error as "Resource not found". so i tried including all my packages as-
<context:component-scan base-package="com.webProject.controller"></context:component-scan>
<context:component-scan base-package="com.webProject.dao"></context:component-scan>
<context:component-scan base-package="com.webProject.model"></context:component-scan> but then also i get same "resource not found" error. i tried another way as mentioned in another thread - http://stackoverflow.com/questions/7914363/injection-of-autowired-dependencies-failed
<context:component-scan base-package="com.webProject">
<context:include-filter type="aspectj" expression="com.webProject.*" />
</context:component-scan>
but then also same result - "Resource not found".
so only when i give this base-package="com.webProject.controller", then i dont get "Resource not found error", but then it get another error -
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentController': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.webProject.dao.IStudentDao
com.webProject.controller.StudentController.studentDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching
bean of type [com.webProject.dao.IStudentDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
then i tried to inject the studentDao as , then i also i get an error.
I am using Tomcat to deploy this artifact. and using maven to build this project. i am not sure how it spring+ hibernate+ maven project works in tomcat?
I have recently started programming using spring and hibernate and this is my first project using these technologies. so please pardon me if i am making some basic mistake.
can you please help me with some solution.
student Dao -
package com.webProject.dao;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.webProject.model.*;
public abstract class AbstractHibernateDAOImpl implements AbstractDao {
#Autowired
private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
protected Class domainClass = getDomainClass();
/**
* Method to return the class of the domain object
*/
protected abstract Class getDomainClass();
#SuppressWarnings("unchecked")
public PersistentObject load(Long id) {
return (PersistentObject) getHibernateTemplate().load(domainClass, id);
}
public void update(PersistentObject t) {
getHibernateTemplate().update(t);
}
public void save(PersistentObject t) {
getHibernateTemplate().save(t);
}
public void delete(PersistentObject t) {
getHibernateTemplate().delete(t);
}
#SuppressWarnings("unchecked")
public List<PersistentObject> getList() {
return (getHibernateTemplate().find("from " + domainClass.getName()
+ " x"));
}
public void deleteById(Long id) {
Object obj = load(id);
getHibernateTemplate().delete(obj);
}
#SuppressWarnings("unchecked")
public void deleteAll() {
getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
String hqlDelete = "delete " + domainClass.getName();
int deletedEntities = session.createQuery(hqlDelete)
.executeUpdate();
return null;
}
});
}
public int count() {
List list = getHibernateTemplate().find(
"select count(*) from " + domainClass.getName() + " x");
Integer count = (Integer) list.get(0);
return count.intValue();
}
}
student dao interface -
package com.webProject.dao;
public interface IStudentDao extends AbstractDao{
}
student dao implementation -
package com.webProject.dao;
import org.springframework.stereotype.Repository;
import com.webProject.model.Student;
#Repository ("studentDao")
public class StudentDaoImpl extends AbstractHibernateDAOImpl implements IStudentDao{
#Override
protected Class getDomainClass() {
return Student.class;
}
}
If your DAO classes is placed in different packages with controller classes then you should change your component scan element:
<context:component-scan base-package="com.webProject">
Also check that you have annotated your DAO classes with #Repository (or #Component) annotation.