Spring #Resource null pointer exception - java

I'm creating a Spring MVC application. And I have a Basket bean that has few autowired beans in in.
#Component
public class Basket {
#Autowired
#Qualifier("CPContainer")
private CPContainer cpContainer;
#Autowired
#Qualifier("FBContainer")
private FBContainer fbContainer;
public CPContainer getCpContainer() {
return cpContainer;
}
public void setCpContainer(CPContainer cpContainer) {
this.cpContainer = cpContainer;
}
public FBContainer getFbContainer() {
return fbContainer;
}
public void setFbContainer(FBContainer fbContainer) {
this.fbContainer = fbContainer;
}
Autowired beans CPContainer and FBContainer have List inside of them wired with list in dispather-servltet.xml via #Resource annotation:
#Component
public class FBContainer implements Container {
#Resource(name = "FBList")
private List<FBProduct> products;
private int id;
private int amount;
#Override
public List<FBProduct> getProducts() {
return products;
}
#Override
public FBProduct getProductById(int id) {
return products.get(id);
}
dispatcher-servltet.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans ...
<mvc:annotation-driven/>
<context:component-scan base-package="com.concrete"/>
<util:list id="FBList" value-type="com.concrete.pojo.product.FBProduct">
<bean id="fb1" class="com.concrete.pojo.product.FBProduct">
<property name="id" value="0"/>
<property name="mass" value="1000"/>
<property name="l" value="8980"/>
<property name="b" value="1490"/>
<property name="h" value="220"/>
</bean>
<bean id="fb2" class="com.concrete.pojo.product.FBProduct">
<property name="id" value="1"/>
<property name="mass" value="2000"/>
<property name="l" value="8980"/>
<property name="b" value="1190"/>
<property name="h" value="220"/>
</bean>
<bean id="fb3" class="com.concrete.pojo.product.FBProduct">
<property name="id" value="2"/>
<property name="mass" value="3000"/>
<property name="l" value="7180"/>
<property name="b" value="1490"/>
<property name="h" value="220"/>
</bean>
</util:list>
<bean id="FBContainer" class="com.concrete.pojo.container.FBContainer">
<property name="products" ref="FBList"/>
</bean>
<bean id="CPContainer" class="com.concrete.pojo.container.CPContainer">
<property name="products" ref="CPList"/>
</bean>
</beans>
I'm adding Basket class to a model as model attribute, wich I intend to use in jsp page to get data from Container's List(Like FBProducts in FBContainer). But when i try to access a List I get null pointer exception :
java.lang.NullPointerException
com.concrete.pojo.container.FBContainer.getProductById(FBContainer.java:25)
com.concrete.pojo.container.Basket.calculateMass(Basket.java:24)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
javax.el.BeanELResolver.invoke(BeanELResolver.java:183)
org.apache.jasper.el.JasperELResolver.invoke(JasperELResolver.java:139)
org.apache.el.parser.AstValue.getValue(AstValue.java:174)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:950)
org.apache.jsp.calculate_jsp._jspService(calculate_jsp.java:93)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:314)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1069)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1008)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
MainController.class :
#Controller
public class MainController {
#Autowired
#Qualifier("basket")
private Basket basket;
#RequestMapping(value = "/calculate",method = RequestMethod.POST)
public String calculate(Model model,Basket basket){
model.addAttribute("Basket",basket);
return "calculate";
}
}

I think i found the solution. It appears I was adding wrong object to model of calculate method inside MainController :
#RequestMapping(value = "/calculate",method = RequestMethod.GET)
public String calculate(Model model,Basket basket){
model.addAttribute("Basket",basket);
return "calculate";
}
So, I removed Basket argument from method and NullPointerException is solved :
#RequestMapping(value = "/calculate",method = RequestMethod.GET)
public String calculate(Model model){
model.addAttribute("Basket",basket);
return "calculate";
}

Related

Spring security jdbc authentication using UserDetailsService with custom login form not working

People I need some help with this subject.. I am really new using Spring Security and I am trying to use a custom login form with database authentication, but I have not gotten positive results.
Currently my application is throwing this Exception when I hit the button login in me web page:
org.springframework.security.authentication.InternalAuthenticationServiceException
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:125)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:143)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:167)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:192)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:93)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:120)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
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:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at com.alcaldia.lineatransportealcaldiafalcon.service.CustomUserDetailsService.loadUserByUsername(CustomUserDetailsService.java:28)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
Here are the correspondig code:
customUserDetailsService
#Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{
#Autowired
private UserService userService;
#Transactional(readOnly=true)
public UserDetails loadUserByUsername(String ssoId)
throws UsernameNotFoundException {
//User user = userService.findBySso(ssoId);
User user = userService.findBySso(ssoId);
System.out.println("User : "+user);
if(user==null){
System.out.println("User not found");
throw new UsernameNotFoundException("Username not found");
}
return new org.springframework.security.core.userdetails.User(user.getSsoId(), user.getPassword(),
user.getState().equals("Active"), true, true, true, getGrantedAuthorities(user));
}
private List<GrantedAuthority> getGrantedAuthorities(User user){
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for(UserProfile userProfile : user.getUserProfiles()){
System.out.println("UserProfile : "+userProfile);
authorities.add(new SimpleGrantedAuthority("ROLE_"+userProfile.getType()));
}
System.out.print("authorities :"+authorities);
return authorities;
}
}
UserService
public interface UserService {
User findById(int id);
User findBySso(String sso);
}
UserServiceImpl
#Service("userService")
public class UserServiceImpl implements UserService{
private static Log logger = LogFactory.getLog(UserServiceImpl.class);
#Autowired
private UserDao dao;
#Transactional
public User findById(int id) {
return dao.findById(id);
}
#Transactional
public User findBySso(String sso) {
System.err.println("ESTOY EN EL USERSERVICEIMPL");
logger.error("ESTOY EN EL USERSERVICEIMPL " + sso);
logger.error("****************************");
return dao.findBySSO(sso);
}
}
UserDao
public interface UserDao {
User findById(int id);
User findBySSO(String sso);
}
userDaoImpl
#Repository("userDao")
public class UserDaoImpl extends AbstractDao<Integer, User> implements UserDao {
private static Log logger = LogFactory.getLog(UserDaoImpl.class);
public User findById(int id) {
return getByKey(id);
}
public User findBySSO(String sso) {
System.err.println("ESTOY EN EL userdaoimpl");
logger.error("ESTOY EN EL userdaoimpl " + sso);
logger.error("****************************");
Criteria crit = createEntityCriteria();
crit.add(Restrictions.eq("ssoId", sso));
return (User) crit.uniqueResult();
}
}
AbstractDao
public abstract class AbstractDao<PK extends Serializable, T> {
private final Class<T> persistentClass;
#SuppressWarnings("unchecked")
public AbstractDao(){
this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
}
#PersistenceContext
EntityManager em;
#SuppressWarnings("unchecked")
public T getByKey(PK key) {
return (T) em.find(persistentClass, key);
//return (T) getSession().get(persistentClass, key);
}
public void persist(T entity) {
em.persist(entity);
}
public void delete(T entity) {
em.remove(entity);
}
protected Criteria createEntityCriteria(){
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> criteria = cb.createQuery(persistentClass);
return (Criteria) criteria;
}
}
and my security conf
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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-4.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<http auto-config="true" >
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/home" access="permitAll" />
<intercept-url pattern="/admin**" access="hasRole('ADMIN')" />
<intercept-url pattern="/dba**" access="hasRole('ADMIN') and hasRole('DBA')" />
<form-login login-page="/login"
username-parameter="ssoId"
password-parameter="password"
authentication-failure-url="/Access_Denied" />
<csrf/>
</http>
<authentication-manager >
<authentication-provider user-service-ref="customUserDetailsService"/>
</authentication-manager>
<beans:bean id="customUserDetailsService" class="com.alcaldia.lineatransportealcaldiafalcon.service.CustomUserDetailsService" />
</beans:beans>
But I am getting NPE.. I've looked into another examples but somehow none of them have worked for me :/ This example It has been the only one that "worked" but it is not working completely yet.
Please, help me out with this, What I am missing?
EDIT: I am adding the servlet-context.xml
<mvc:annotation-driven/>
<context:component-scan base-package="com.alcaldia.lineatransportealcaldiafalcon.service" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver" />
<property name="url" value="jdbc:jtds:sqlserver://localhost/:1433;DatabaseName=learning" />
<property name="username" value="sa" />
<property name="password" value="Osman1994*" />
</bean>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="dataSource" ref="dataSource"/>
</bean> -->
<!-- Configure the entity manager factory bean -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.alcaldia.lineatransportealcaldiafalcon.model"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Configure the transaction manager bean -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- Enable annotation driven transaction management -->
<tx:annotation-driven/>
<!-- Transaction Manager
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean> -->
<!-- Enable #Transactional annotation
<tx:annotation-driven/> -->

how to solve org.hibernate.TypeMismatchException?

I try to develop some server program using spring mvc and hibernate.
At my tables, some tables have two primray keys.
So, I want to use these keys.
Simply, I use double #Id annotations.
In the result, I got org.hibernate.TypeMismatchException.
Although I searched to solve error, I can't solve this problem...
help me please.
This is my model class.
package kr.ac.jbnu.jinggumdari.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.NaturalId;
import org.hibernate.annotations.Parameter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name="festival_info")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Interest implements Serializable{
#Id
#Column(name="interest")
private String interest;
#Id
#Column(name="festival_number", unique=true, nullable=false)
#GeneratedValue(generator="gen")
#GenericGenerator(name="gen", strategy="foreign", parameters=#Parameter(name="property", value="festival_info"))
private String festivalNumber;
public Interest(){
festivalNumber = "";
interest = "";
}
public Interest(String festivalNumber, String interest) {
this.festivalNumber = festivalNumber;
this.interest = interest;
}
public String getFestivalNumber() {
return festivalNumber;
}
public void setFestival_number(String festivalNumber) {
this.festivalNumber = festivalNumber;
}
public String getInterest() {
return interest;
}
public void setInterest(String interest) {
this.interest = interest;
}
#Override
public String toString(){
return festivalNumber + "," + interest;
}
}
This is my servlet-context.xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- 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>
<beans:bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<beans:property name="favorPathExtension" value="true" />
<beans:property name="ignoreAcceptHeader" value="true" />
<beans:property name="mediaTypes">
<beans:map>
<beans:entry key="json" value="application/json" />
<beans:entry key="html" value="text/html" />
</beans:map>
</beans:property>
</beans:bean>
<context:component-scan base-package="kr.ac.jbnu.jinggumdari" />
<beans:bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/jinggumdari" />
<beans:property name="username" value="root" />
<beans:property name="password" value="mysql1234" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>kr.ac.jbnu.jinggumdari.model.Member</beans:value>
<beans:value>kr.ac.jbnu.jinggumdari.model.Festival</beans:value>
<beans:value>kr.ac.jbnu.jinggumdari.model.FestivalImage</beans:value>
<beans:value>kr.ac.jbnu.jinggumdari.model.Interest</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
<beans:property name="packagesToScan" value="com.hibernate.yourpackage" />
</beans:bean>
<beans:bean id="memberDAO" class="kr.ac.jbnu.jinggumdari.DAO.MemberDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="memberService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.MemberServiceImpl">
<beans:property name="memberDAO" ref="memberDAO"></beans:property>
</beans:bean>
<beans:bean id="festivalDAO" class="kr.ac.jbnu.jinggumdari.DAO.FestivalDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="festivalService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.FestivalServiceImpl">
<beans:property name="festivalDAO" ref="festivalDAO"></beans:property>
</beans:bean>
<beans:bean id="festivalImageDAO" class="kr.ac.jbnu.jinggumdari.DAO.FestivalImageDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="festivalImageService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.FestivalImageServiceImpl">
<beans:property name="festivalImageDAO" ref="festivalImageDAO"></beans:property>
</beans:bean>
<beans:bean id="interestDAO" class="kr.ac.jbnu.jinggumdari.DAO.InterestDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="interestService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.InterestServiceImpl">
<beans:property name="interestDAO" ref="interestDAO"></beans:property>
</beans:bean>
<beans:bean id="reviewDAO" class="kr.ac.jbnu.jinggumdari.DAO.ReviewDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="reviewService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.ReviewServiceImpl">
<beans:property name="reviewDAO" ref="reviewDAO"></beans:property>
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
</beans:beans>
This is my DAO.
package kr.ac.jbnu.jinggumdari.DAO;
import java.util.List;
import kr.ac.jbnu.jinggumdari.model.Interest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
public class InterestDAOImpl implements InterestDAO {
private static final Logger logger = LoggerFactory
.getLogger(FestivalDAOImpl.class);
private SessionFactory sessionFactory;
private boolean isSuccess;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
#Override
#Transactional
public boolean addInterest(Interest interest) {
// TODO Auto-generated method stub
isSuccess = false;
Session session = this.sessionFactory.getCurrentSession();
session.persist(interest);
logger.info("Festival saved successfully, Festival Details=" + interest);
isSuccess = true;
return isSuccess;
}
#Override
#Transactional
public boolean modifyInterest(Interest interest) {
// TODO Auto-generated method stub
isSuccess = false;
Session session = this.sessionFactory.getCurrentSession();
session.update(interest);
logger.info("Festival modified successfully, Festival Details="
+ interest);
isSuccess = true;
return isSuccess;
}
#Override
#Transactional
public boolean removeInterests(String festivalNumber) {
// TODO Auto-generated method stub
isSuccess = false;
Session session = this.sessionFactory.getCurrentSession();
Long numberOfInterests = getNumberOfInterests(festivalNumber, session);
for (int i = 0; i < numberOfInterests; i++) {
Interest targetInterest = (Interest) session.load(Interest.class,
festivalNumber);
if (targetInterest != null) {
session.delete(targetInterest);
}
logger.info("Interest deleted successfully, Interest details="
+ targetInterest);
}
isSuccess = true;
return isSuccess;
}
#Override
#Transactional
public List<Interest> getInterests(String festivalNumber) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
List<Interest> interestsList = session.createQuery("from Interest")
.list();
for (Interest i : interestsList) {
logger.info("Person List::" + i);
}
return interestsList;
}
#Transactional
private Long getNumberOfInterests(String festivalNUmber, Session session) {
String hql = "Select count(*) from Interest where festival_number='"
+ festivalNUmber + "'";
List list = session.createQuery(hql).list();
return (Long) list.get(0);
}
}
This is error stack.
org.hibernate.TypeMismatchException: Provided id of the wrong type for class kr.ac.jbnu.jinggumdari.model.Interest. Expected: class kr.ac.jbnu.jinggumdari.model.Interest, got class java.lang.String
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:134)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1106)
at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.getReference(SessionImpl.java:2564)
at org.hibernate.internal.SessionImpl.load(SessionImpl.java:981)
at kr.ac.jbnu.jinggumdari.DAO.InterestDAOImpl.removeInterests(InterestDAOImpl.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy54.removeInterests(Unknown Source)
at kr.ac.jbnu.jinggumdari.serviceImplementation.InterestServiceImpl.removeInterests(InterestServiceImpl.java:31)
at kr.ac.jbnu.jinggumdari.controller.JinggumdariController.test2(JinggumdariController.java:309)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
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 org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
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:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
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:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Your problem is that you are using two #Id annotations in the same entity, you would rather use #EmbeddeId instead, so change this code:
#Id
#Column(name="interest")
private String interest;
#Id
#Column(name="festival_number", unique=true, nullable=false)
#GeneratedValue(generator="gen")
#GenericGenerator(name="gen", strategy="foreign", parameters=#Parameter(name="property", value="festival_info"))
private String festivalNumber;
To the following code:
public class Interest implements Serializable{
#EmbeddedId
private InterestId id;
//getters and setters and the rest of your code go here
}
And the InterestId class:
#Embeddable
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name="interest")
private String interest;
#Column(name="festival_number", unique=true, nullable=false)
#GeneratedValue(generator="gen")
#GenericGenerator(name="gen", strategy="foreign", parameters=#Parameter(name="property", value="festival_info"))
private String festivalNumber;
// and getters and setters here
}
You can refer to this tutorial and the Documentation here for further information.
You cannot use 2 #Id annotations for a composite primary key. You have to use #EmbeddedId Check this documentation and this Stackoverflow link.

org.springframework.transaction.CannotCreateTransactionException

I am getting the below error while trying to call a service class
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.NullPointerException
org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:431)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:372)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:417)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:255)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
com.plm.conn.model.QueueService$$EnhancerBySpringCGLIB$$9405c9f4.getAll()
com.plm.conn.hcontroller.HomeController.home(HomeController.java:67)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:685)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
My servlet-context.xml
<!-- Derby configuration -->
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName"
value="org.apache.derby.jdbc.ClientDriver" />
<beans:property name="url"
value="jdbc:derby://localhost:1527//office;create=false" />
<beans:property name="username" value="office" />
</beans:bean>
<!-- EntityManagerFactory -->
<beans:bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="jtaDataSource" ref="dataSource" />
<beans:property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<beans:property name="packagesToScan" value="com.plm.conn.model" />
</beans:bean>
<!-- Transaction adapter -->
<beans:bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<beans:property name="databasePlatform"
value="org.hibernate.dialect.DerbyDialect" />
<beans:property name="showSql" value="true" />
<beans:property name="generateDdl" value="false" />
</beans:bean>
<!-- Transaction Manager -->
<beans:bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="emf" />
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<beans:bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- tx:annotation-driven /-->
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.plm.conn.model" />
Service
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional
#Component
#Service
public class QueueService implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory
.getLogger(QueueService.class);
#PersistenceContext
private EntityManager em;
#Transactional
public void addQueue(Queue queue) {
logger.info(" info..."+em.toString());
em.persist(queue);
}
#Transactional
public List<Queue> getAll() {
TypedQuery<Queue> query = em.createNamedQuery("Queue.findAll",
Queue.class);
logger.info(" info..." + query.getResultList());
return query.getResultList();
}
}
and my controller where i am calling the queue
package com.plm.conn.hcontroller;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.plm.conn.model.Queue;
import com.plm.conn.model.QueueService;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory
.getLogger(HomeController.class);
#Autowired
private QueueService queueSvc;
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
public String home(Locale locale, Model model, HttpServletRequest request,
HttpServletResponse response) {
Queue queue = new Queue();
//queue.setMsgidProd("1212121212");
//queueSvc.addQueue(queue);
logger.info(queueSvc.toString());
model.addAttribute("list", queueSvc.getAll());
return "home";
}
}
I can see some improvement needs to be done in the code.
1.Why you have annotated QueueService class with #Component,#Repository and #Service annotation all together,as per the code it contains,it should be annotated only with #Repository.
2.You have used #Transactional annotation at the class level,remove it from the individual method from this class.
3.In your servlet-context.xml file,you have below line
<context:component-scan base-package="com.plm.conn.model" />
make sure that you should have configured it correctly,it should scan the spring managed component,not your database entity,because according to your servlet-context.xml file,"com.plm.conn.model" is your entity package(see <beans:property name="packagesToScan" value="com.plm.conn.model" />)
I want to persist data without persistence.xml file. this is why I use Queue.java entity class which is in the com.plm.conn.model
I am new to the Spring I learned that we can persist the data without using persistence class. I modified servlet-context.xml as follows
<!-- Derby configuration -->
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName"
value="org.apache.derby.jdbc.ClientDriver" />
<beans:property name="url"
value="jdbc:derby://localhost:1527//plmbridge;create=false" />
<beans:property name="username" value="plmt" />
</beans:bean>
<!-- EntityManagerFactory -->
<beans:bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<beans:property name="packagesToScan" value="com.plm.conn.model" />
</beans:bean>
<!-- Transaction adapter -->
<beans:bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<beans:property name="databasePlatform"
value="org.hibernate.dialect.DerbyDialect" />
<beans:property name="showSql" value="true" />
<beans:property name="generateDdl" value="false" />
</beans:bean>
<!-- Transaction Manager -->
<beans:bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="emf" />
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<beans:bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- tx:annotation-driven /-->
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.plm.conn.model" />
and the Queue.java file here
package com.plm.conn.model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the QUEUE database table.
*
*/
#Entity
#Table(name="QUEUE")
#NamedQuery(name="Queue.findAll", query="SELECT q FROM Queue q")
public class Queue implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.TABLE)
#Column(name="QUEUE_ID", unique=true, nullable=false)
private int queueId;
#Column(length=250)
private String container;
private long expiration;
#Column(nullable=false, length=100)
private String id;
#Lob
private byte[] msg;
#Column(name="MSGID_PROD", length=250)
private String msgidProd;
#Column(name="MSGID_SEQ")
private long msgidSeq;
private long priority;
#Column(length=250)
private String xid;
//bi-directional one-to-one association to Completedjob
#OneToOne(mappedBy="queue")
private Completedjob completedjob;
//bi-directional one-to-one association to Failedjob
#OneToOne(mappedBy="queue")
private Failedjob failedjob;
public Queue() {
}
public int getQueueId() {
return this.queueId;
}
public void setQueueId(int queueId) {
this.queueId = queueId;
}
public String getContainer() {
return this.container;
}
public void setContainer(String container) {
this.container = container;
}
public long getExpiration() {
return this.expiration;
}
public void setExpiration(long expiration) {
this.expiration = expiration;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public byte[] getMsg() {
return this.msg;
}
public void setMsg(byte[] msg) {
this.msg = msg;
}
public String getMsgidProd() {
return this.msgidProd;
}
public void setMsgidProd(String msgidProd) {
this.msgidProd = msgidProd;
}
public long getMsgidSeq() {
return this.msgidSeq;
}
public void setMsgidSeq(long msgidSeq) {
this.msgidSeq = msgidSeq;
}
public long getPriority() {
return this.priority;
}
public void setPriority(long priority) {
this.priority = priority;
}
public String getXid() {
return this.xid;
}
public void setXid(String xid) {
this.xid = xid;
}
public Completedjob getCompletedjob() {
return this.completedjob;
}
public void setCompletedjob(Completedjob completedjob) {
this.completedjob = completedjob;
}
public Failedjob getFailedjob() {
return this.failedjob;
}
public void setFailedjob(Failedjob failedjob) {
this.failedjob = failedjob;
}
}
I am able to query the tables but I cant store the data I get the error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: error performing isolated work
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:965)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
ERROR 42X05: Table/View 'HIBERNATE_SEQUENCES' does not exist.
org.apache.derby.client.am.ClientStatement.completeSqlca(Unknown Source)
org.apache.derby.client.net.NetStatementReply.parsePrepareError(Unknown Source)
org.apache.derby.client.net.NetStatementReply.parsePRPSQLSTTreply(Unknown Source)
org.apache.derby.client.net.NetStatementReply.readPrepareDescribeOutput(Unknown Source)
org.apache.derby.client.net.StatementReply.readPrepareDescribeOutput(Unknown Source)
org.apache.derby.client.net.NetStatement.readPrepareDescribeOutput_(Unknown Source)
org.apache.derby.client.am.ClientStatement.readPrepareDescribeOutput(Unknown Source)
org.apache.derby.client.am.ClientPreparedStatement.readPrepareDescribeInputOutput(Unknown Source)
org.apache.derby.client.am.ClientPreparedStatement.flowPrepareDescribeInputOutput(Unknown Source)
org.apache.derby.client.am.ClientPreparedStatement.prepare(Unknown Source)
org.apache.derby.client.am.ClientConnection.prepareStatementX(Unknown Source)
org.apache.derby.client.am.ClientConnection.prepareStatement(Unknown Source)
org.hibernate.id.MultipleHiLoPerTableGenerator.prepareStatement(MultipleHiLoPerTableGenerator.java:243)
org.hibernate.id.MultipleHiLoPerTableGenerator.access$200(MultipleHiLoPerTableGenerator.java:86)
org.hibernate.id.MultipleHiLoPerTableGenerator$1.execute(MultipleHiLoPerTableGenerator.java:159)
org.hibernate.id.MultipleHiLoPerTableGenerator$1.execute(MultipleHiLoPerTableGenerator.java:152)
org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:72)
org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:51)
org.hibernate.engine.transaction.internal.jdbc.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:74)
org.hibernate.id.MultipleHiLoPerTableGenerator$2.getNextValue(MultipleHiLoPerTableGenerator.java:221)
org.hibernate.id.enhanced.LegacyHiLoAlgorithmOptimizer.generate(LegacyHiLoAlgorithmOptimizer.java:77)
org.hibernate.id.MultipleHiLoPerTableGenerator.generate(MultipleHiLoPerTableGenerator.java:218)
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:291)
com.sun.proxy.$Proxy33.persist(Unknown Source)
com.plm.conn.model.QueueService.addQueue(QueueService.java:37)
com.plm.conn.model.QueueService$$FastClassBySpringCGLIB$$6b3c7d41.invoke(<generated>)
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
com.plm.conn.model.QueueService$$EnhancerBySpringCGLIB$$77572cff.addQueue(<generated>)
com.plm.conn.hcontroller.HomeController.home(HomeController.java:63)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:685)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Getting java.lang.NullPointerException while getSession().save(entity);

I want to add object data and want to save in DB table, everything working fine but it gives me an error :
java.lang.NullPointerException
on line getSession().save(entity);
I have called this method in code :
#Service
public class AddCategoryProcessor implements ICommandProcessor<AddCategory> {
#Autowired
private IPatronCategoryRepository patronCategoryRepository = new PatronCategoryRepository();
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void Process(AddCategory command){
PatronCategory entity = new PatronCategory();
entity.setCategoryName(command.getCategoryName());
try
{
patronCategoryRepository.save(entity);
}catch (Exception e){
e.printStackTrace();
}
}
}
following is my xml file :
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/abc"/>
<property name="username" value="postgres"/>
<property name="password" value="pwd"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.ngl.domain"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
Here is a getSession() method :
#Override
public Session getSession() {
return getSessionFactory().getCurrentSession();
}
Here is a sessionFactory declaration :
protected SessionFactory sessionFactory;
Any guesses why it's NULLPOINTEREXCEPTION ??
UPDATE :
java.lang.NullPointerException
at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:32)
at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:16)
at com.ngl.controllerapis.BaseApiController.ProcessRequest(BaseApiController.java:29)
at com.ngl.controllerapis.PatronCategoryController.addCategory(PatronCategoryController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
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 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.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
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:744)
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
and xml for transaction manager
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
in repository
#Autowired
protected SessionFactory sessionFactory;
Your config is a bit incomplete. You should delegate session management completely to Spring
Add in you spring xml file:
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Then, in your PatronCategoryRepository class, extend HibernateDaoSupport and add this constructor:
public class PatronCategoryRepository extends HibernateDaoSupport implements IPatronCategoryRepository{
#Autowired
public PatronCategoryRepository(HibernateTemplate hibernateTemplate) {
super();
super.setHibernateTemplate(hibernateTemplate);
}
[...]
}
In AddCategoryProcessor, leave the definition of the repository like this:
#Autowired
private IPatronCategoryRepository patronCategoryRepository;
And finally your method:
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void Process(AddCategory command){
PatronCategory entity = new PatronCategory();
entity.setCategoryName(command.getCategoryName());
try
{
getHibernateTemplate.save(entity);
}catch (Exception e){
e.printStackTrace();
}
}
In case you still need to access directy the SessionFactory, the only thing you have to do is inject it into PatronCategoryRepository:
#Repository
public class PatronCategoryRepository implements IPatronCategoryRepository{
#Autowired
protected SessionFactory sessionFactory;
public PatronCategoryRepository() {
}
public PatronCategory save(PatronCategory entity){
return getSession().save(entity);
}
private Session getSession() {
return sessionFactory.getCurrentSession();
}
}
And remember to remove the new clause from AddCategoryProcessor, leaving it like this:
#Autowired
private IPatronCategoryRepository patronCategoryRepository;
Employee.java
package com.javacodegeeks.snippets.enterprise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "Employee1")
public class Employee implements Serializable {
#Id
#Column(name = "ID")
private int id;
#Column(name = "NAME")
private String name;
#Column(name = "AGE")
private int age;
public Employee() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
EmployeeDao.java
package com.javacodegeeks.snippets.enterprise.dao;
import com.javacodegeeks.snippets.enterprise.model.Employee;
public interface EmployeeDAO {
public void saveEmployee(Employee employee);
Employee findEmployeeById(int id);
void updateEmployee(Employee employee);
void deleteEmployee(Employee employee);
}
EmployeeDaoImpl.java
package com.javacodegeeks.snippets.enterprise.dao;
import java.io.Serializable;
import org.hibernate.SessionException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.javacodegeeks.snippets.enterprise.model.Employee;
public class EmployeeDAOImpl implements EmployeeDAO {
private HibernateTemplate template;
private SessionFactory sessionFactory;
#Autowired
public void setTemplate(HibernateTemplate template) {
this.template = template;
// template.setSessionFactory(sessionFactory);
}
public void setSessionFactory(SessionFactory sessionFactory) {
new HibernateTemplate(sessionFactory);
}
/*
* public void saveEmployee(Employee employee) {
* sessionFactory.getCurrentSession().save(employee);
*
* }
*/
public Employee findEmployeeById(int id) {
return (Employee) sessionFactory.getCurrentSession().get(
Employee.class, id);
}
public void updateEmployee(Employee employee) {
sessionFactory.getCurrentSession().update(employee);
}
public void deleteEmployee(Employee employee) {
sessionFactory.getCurrentSession().delete(employee);
}
public void saveEmployee(Employee employee) {
sessionFactory.getCurrentSession().persist(employee);
template.saveOrUpdate(employee);
}
}
Application COntext.xml
<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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package="com.javacodegeeks.snippets.enterprise.*" />
<!-- <tx:annotation-driven/> -->
<bean id="dataSource" 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/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.javacodegeeks.snippets.enterprise.model.Employee</value>
</list>
</property>
<!-- <property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property> -->
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> -->
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="d" class="com.javacodegeeks.snippets.enterprise.dao.EmployeeDAOImpl">
<property name="template" ref="template"></property>
</bean>
</beans>
pleas ehelp me :-)

Spring security No Hibernate Session bound to thread

I searched the forum for this answer, but i could not find a solution.
I have configured my transaction manger bean
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
I have configured my session factory.
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="url" value="jdbc:derby://localhost:1527/hibernate"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>org.krams.tutorial.domain.Person</value>
<value>org.krams.tutorial.domain.UserRole</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
My daoImpl and Service class have #repository and #transactional tag
#Repository("personDao")
public class PersonDAOImpl implements PersonDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public void savePerson(Person person) {
sessionFactory.getCurrentSession().saveOrUpdate (person);
}
#Override
public Person findByName(String name){
String query = "select * from Person p where p.username='"+name+"'";
Person person = (Person) sessionFactory.getCurrentSession().createQuery(query);
return person;
}
}
#Service("userService")
#Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public class PersonServiceImpl implements PersonService{
#Autowired
private PersonDAO personDao;
#Override
#Transactional(propagation=Propagation.SUPPORTS, readOnly=false)
public void savePerson(Person person) {
personDao.savePerson(person);
}
#Override
#Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public Person findByName(String name){
return personDao.findByName(name);
}
}
I have one more service class for Spring Security database implementation
#Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private PersonService userService;
#Autowired
private Assembler assembler;
#Transactional(readOnly = true)
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
try {
Person person = userService.findByName(username);
return (UserDetails) assembler.buildUserFromUserEntity(person);
} catch (NoResultException e) {
throw new UsernameNotFoundException(e.getLocalizedMessage());
}
}
}
stacktrace:
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:544)
at org.krams.tutorial.dao.PersonDAOImpl.findByName(PersonDAOImpl.java:30)
at org.krams.tutorial.service.PersonServiceImpl.findByName(PersonServiceImpl.java:40)
at org.krams.tutorial.service.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:37)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:82)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:124)
at org.springframework.security.authentication.ProviderManager.doAuthentication(ProviderManager.java:120)
at org.springframework.security.authentication.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:48)
at org.springframework.security.authentication.ProviderManager.doAuthentication(ProviderManager.java:138)
at org.springframework.security.authentication.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:48)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:97)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)
I am confused as where did i go wrong. Please guys help me out.
Looks like you have missed to enable the transaction support.
Add tx:annotation-driven to the configuration:
<beans
...
xmlns:tx="http://www.springframework.org/schema/tx"
...
xsi:schemaLocation="...
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
...
<tx:annotation-driven transaction-manager="transactionManager" />

Categories