Transaction error in Spring - java

I have a project
https://github.com/ivartanian/onlinecontrol
in Spring MVC + JPA, initially worked with the Spring configuration through XML. Now I am trying to set up the project through JAVA Config (without XML). The project starts, but when I create a new user(entity User), an error transaction. But if I create another Entity this error not occur. If this XML configuration error does not occur too.
Please tell me what the cause of the error.
I would be glad of any help
My XML config is:
<context:component-scan
base-package="com.vizaco.onlinecontrol.service"/>
<!-- enables scanning for #Transactional annotations -->
<tx:annotation-driven/>
<!-- ========================= DATASOURCE DEFINITION ========================= -->
<!-- Configurer that replaces ${...} placeholders with values from a properties file -->
<!-- (in this case, JDBC-related settings for the dataSource definition below) -->
<context:property-placeholder location="classpath:spring/data-access.properties" system-properties-mode="OVERRIDE"/>
<!-- Database initializer. If any of the script fails, the initialization stops. -->
<!-- As an alternative, for embedded databases see <jdbc:embedded-database/>. -->
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="${jdbc.initLocation}"/>
<jdbc:script location="${jdbc.dataLocation}"/>
</jdbc:initialize-database>
<!-- DataSource configuration for the Jetty jdbc connection -->
<bean id="dataSource" class="org.hsqldb.jdbc.JDBCDataSource">
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<context:component-scan base-package="com.vizaco.onlinecontrol.dao.jpa"/>
<context:component-scan base-package="com.vizaco.onlinecontrol.security"/>
<context:component-scan base-package="com.vizaco.onlinecontrol.configuration"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}" p:showSql="${jpa.showSql}"/>
<!-- the 'database' parameter refers to the database dialect being used.
By default, Hibernate will use a 'HSQL' dialect because 'jpa.database' has been set to 'HSQL'
inside file spring/data-access.properties
-->
</property>
</bean>
<!-- Transaction manager for a single JPA EntityManagerFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<!-- Voters -->
<bean id="accessDecisionManager"
class="org.springframework.security.access.vote.AffirmativeBased">
<constructor-arg name="decisionVoters">
<list>
<bean class="org.springframework.security.access.vote.RoleVoter"/>
</list>
</constructor-arg>
</bean>
<!--<bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">-->
<!--<property name="permissionEvaluator" ref="customPermissionEvaluator"/>-->
<!--</bean>-->
<!--<bean id="customPermissionEvaluator" class="com.vizaco.onlinecontrol.security.impl.CustomPermissionEvaluator"/>-->
<!-- SECURITY -->
<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<constructor-arg name="strength" value="11"/>
</bean>
<!-- Validators -->
<bean id="userValidator" class="com.vizaco.onlinecontrol.validators.UserValidator"/>
<!-- Messages -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="ru"/>
</bean>
<!-- Converters -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.vizaco.onlinecontrol.converters.StringToClazz"/>
<bean class="com.vizaco.onlinecontrol.converters.StringToUser"/>
</set>
</property>
</bean>
</beans>
My Java config is:
#Configuration
#EnableWebMvc
#EnableAspectJAutoProxy
#EnableTransactionManagement
#ComponentScan({
"com.vizaco.onlinecontrol.aspects",
"com.vizaco.onlinecontrol.configuration",
"com.vizaco.onlinecontrol.controller",
"com.vizaco.onlinecontrol.dao",
"com.vizaco.onlinecontrol.model",
"com.vizaco.onlinecontrol.validators",
"com.vizaco.onlinecontrol.security",
"com.vizaco.onlinecontrol.service"})
#PropertySource("classpath:spring/data-access.properties")
public class WebConfig extends WebMvcConfigurerAdapter implements TransactionManagementConfigurer {
#Autowired
Environment environment;
#Autowired
private ClazzService clazzService;
#Autowired
private UserService userService;
#Autowired
private MethodSecurityMetadataSourceAdvisor sourceAdvisor;
#Bean
public UserDetailsService userDetailsService() {
return new CustomUserDetailsServiceImpl();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public DataSource dataSource() {
JDBCDataSource dataSource = new JDBCDataSource();
dataSource.setUrl(environment.getProperty("jdbc.url"));
dataSource.setUser(environment.getProperty("jdbc.username"));
dataSource.setPassword(environment.getProperty("jdbc.password"));
return dataSource;
}
#Bean
public DataSourceInitializer dataSourceInitializer() {
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(dataSource());
CompositeDatabasePopulator compositeDatabasePopulator = new CompositeDatabasePopulator();
compositeDatabasePopulator.addPopulators(new ResourceDatabasePopulator(new DefaultResourceLoader().getResource(environment.getProperty("jdbc.initLocation"))));
compositeDatabasePopulator.addPopulators(new ResourceDatabasePopulator(new DefaultResourceLoader().getResource(environment.getProperty("jdbc.dataLocation"))));
dataSourceInitializer.setDatabasePopulator(compositeDatabasePopulator);
return dataSourceInitializer;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[]{"com.vizaco.onlinecontrol.model"});
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabase(Database.HSQL);
vendorAdapter.setShowSql(true);
em.setJpaVendorAdapter(vendorAdapter);
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
em.setJpaProperties(properties);
return em;
}
#Bean
public PlatformTransactionManager txManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return txManager();
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/WEB-INF/jsp/**").addResourceLocations("/jsp/");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(true)
.useJaf(false)
.ignoreAcceptHeader(true)
.mediaType("html", MediaType.TEXT_HTML)
.mediaType("json", MediaType.APPLICATION_JSON)
.defaultContentType(MediaType.TEXT_HTML);
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
registry.viewResolver(resolver);
registry.beanName();
}
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToClazz(clazzService));
registry.addConverter(new StringToUser(userService));
}
#Bean(name = "messageSource")
public MessageSource configureMessageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setCacheSeconds(5);
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public CookieLocaleResolver localeResolver() {
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
localeResolver.setDefaultLocale(new Locale("ru"));
return localeResolver;
}
}
The error occurs when you call this.em.persist(user) in the method save(User user):
#Repository
public class JpaUserDaoImpl implements UserDao {
#PersistenceContext
private EntityManager em;
public JpaUserDaoImpl() {
}
public JpaUserDaoImpl(EntityManager em) {
this.em = em;
}
#Override
public User findByEmail(String email) throws DataAccessException {
Query query = this.em.createQuery("SELECT DISTINCT user FROM User user WHERE user.email =:email");
query.setParameter("email", email);
List resultList = query.getResultList();
if (resultList.isEmpty()) {
return null; // handle no-results case
} else {
return (User)resultList.get(0);
}
// return (User) query.getSingleResult();
}
#Override
public User findById(Long id) {
Query query = this.em.createQuery("SELECT DISTINCT user FROM User user WHERE user.id =:id");
query.setParameter("id", id);
List resultList = query.getResultList();
if (resultList.isEmpty()) {
return null; // handle no-results case
} else {
return (User)resultList.get(0);
}
}
#Override
public List<User> getAllUsers() throws DataAccessException {
Query query = this.em.createQuery("SELECT DISTINCT user FROM User user");
return query.getResultList();
}
#Override
public void save(User user) {
if (user == null){
return;
}
if (user.getId() == null) {
this.em.persist(user);
}
else {
this.em.merge(user);
}
}
#Override
public void delete(User user) throws DataAccessException {
if (user == null){
return;
}
this.em.remove(user);
}
}
That error:
javax.persistence.TransactionRequiredException: No transactional EntityManager available
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:275)
at com.sun.proxy.$Proxy64.persist(Unknown Source)
at com.vizaco.onlinecontrol.dao.jpa.JpaUserDaoImpl.save(JpaUserDaoImpl.java:68)
at com.vizaco.onlinecontrol.service.impl.UserServiceImpl.saveUser(UserServiceImpl.java:51)
at com.vizaco.onlinecontrol.controller.UserController.createUser(UserController.java:112)
at com.vizaco.onlinecontrol.controller.UserController$$FastClassBySpringCGLIB$$2ef7ce5a.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:43)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.vizaco.onlinecontrol.controller.UserController$$EnhancerBySpringCGLIB$$9f848f41.createUser(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
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:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:806)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:105)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:550)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1128)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1062)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:113)
at org.eclipse.jetty.server.Server.handle(Server.java:507)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:284)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:237)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:240)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:93)
at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:53)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceRun.produceAndRun(ExecuteProduceRun.java:191)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceRun.run(ExecuteProduceRun.java:126)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:641)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:559)
at java.lang.Thread.run(Thread.java:745)

In the stacktrace, there are no Spring AOP class listed between these two lines:
at com.vizaco.onlinecontrol.service.impl.UserServiceImpl.saveUser(UserServiceImpl.java:51)
at com.vizaco.onlinecontrol.controller.UserController.createUser(UserController.java:112)
Your Dependency Injection is not setup right.. the Controller should be getting a Spring Bean of UserService

Related

javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread

I created my first Spring MVC project with using Hibernate. My DAO layer is using JPA EntityManager for interaction with database.
GenericDao.java:
#Repository
public abstract class GenericDao<T> implements GeneralDao<T> {
private Class<T> className;
public GenericDao(Class<T> className) {
this.className = className;
}
#PersistenceContext
private EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
#Override
public void add(T object) {
try {
getEntityManager().persist(object);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.ADD_ENTITY_FAIL, e);
}
}
#Override
public void update(T object) {
try {
getEntityManager().merge(object);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.UPDATE_ENTITY_FAIL, e);
}
}
#Override
public void remove(T object) {
try {
getEntityManager().remove(object);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.REMOVE_ENTITY_FAIL, e);
}
}
#Override
public T getById(int id) {
try {
return getEntityManager().find(this.className, id);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.GET_BY_ID_ENTITY_FAIL, e);
}
}
public abstract List<T> getAll() throws DaoException;
}
GenericService.java
#Service
public abstract class GenericService<T> implements GeneralService<T> {
private static Logger logger = Logger.getLogger(GenericService.class);
#Autowired
private GenericDao<T> dao;
#Transactional
#Override
public void add(T object) throws ServiceException {
try {
dao.add(object);
} catch (DaoException e) {
logger.debug(e);
throw new ServiceException(e.getMessage());
}
}
#Transactional
#Override
public void update(T object) throws ServiceException {
try {
dao.update(object);
} catch (DaoException e) {
logger.debug(e);
throw new ServiceException(e.getMessage());
}
}
#Transactional
#Override
public void remove(T object) throws ServiceException {
try {
dao.remove(object);
} catch (DaoException e) {
logger.debug(e);
throw new ServiceException(e.getMessage());
}
}
#Transactional(readOnly = true)
#Override
public T getById(int id) throws ServiceException {
try {
return dao.getById(id);
} catch (DaoException e) {
logger.debug(e);
throw new ServiceException(e.getMessage());
}
}
#Transactional(readOnly = true)
#Override
public List<T> getAll() throws ServiceException {
try {
return dao.getAll();
} catch (DaoException e) {
logger.debug(e);
throw new ServiceException(e.getMessage());
}
}
}
UserServiceImpl.java:
#Service
public class UserServiceImpl extends GenericService<User> implements UserService {
private static Logger logger = Logger.getLogger(UserServiceImpl.class);
#Autowired
private UserDao userDao;
#Transactional
#Override
public String checkUser(String userLogin, String userPassword) throws ServiceException {
String namePage = "errorAuthorization";
List<User> userList;
try {
userList = userDao.getByLoginAndPassword(userLogin, userPassword);
} catch (DaoException e) {
logger.debug(e);
throw new ServiceException(e.getMessage());
}
if(userList.size() != 0) {
return UserRoleChecker.defineUserPage(userList.get(0));
}
return namePage;
}
#Transactional
#Override
public void addUser(String userLogin, String userPassword, String userMail) throws ServiceException {
Role role = new Role(0L, RoleType.USER);
User user = new User(0L, userLogin, userPassword, userMail, role);
add(user);
}
}
UserController.java:
#Controller
public class UserController {
private static String className = UserController.class.getName();
private static Logger logger = Logger.getLogger(UserController.class.getName());
#Autowired
private UserService userService;
#RequestMapping(value = "/check_user", method = RequestMethod.POST)
public ModelAndView authorizationUser(HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView();
String returnPage;
try {
returnPage = userService.checkUser(request.getParameter(RequestParameter.USER_LOGIN), request.getParameter(RequestParameter.USER_PASSWORD));
} catch (ServiceException e) {
logger.debug(e);
returnPage = ErrorHandler.returnErrorPage(e.getMessage(), className);
}
modelAndView.setViewName(returnPage);
return modelAndView;
}
#RequestMapping(value = "/add_user", method = RequestMethod.POST)
public ModelAndView registrationUser(HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView();
String returnPage = Page.SUCCESSFUL_REGISTRATION;
try {
userService.addUser(request.getParameter(RequestParameter.USER_LOGIN), request.getParameter(RequestParameter.USER_PASSWORD), request.getParameter(RequestParameter.USER_MAIL));
} catch (ServiceException e) {
logger.debug(e);
returnPage = ErrorHandler.returnErrorPage(e.getMessage(), className);
}
modelAndView.setViewName(returnPage);
return modelAndView;
}
}
root-context.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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.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">
<context:annotation-config />
<context:component-scan base-package="by.netcracker.artemyev.dao" />
<context:component-scan base-package="by.netcracker.artemyev.service" />
<context:component-scan base-package="by.netcracker.artemyev.web" />
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/airline?useSSL=false" />
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="initialSize" value="5"/>
<property name="maxTotal" value="10"/>
</bean>
<bean id="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="by.netcracker.artemyev" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="database" value="MYSQL" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="debug">true</prop>
<prop key="connection.isolation">2</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManager" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
</beans>
Logs:
org.springframework.web.servlet.FrameworkServlet 2017-05-10 22:23:59,107 DEBUG - Could not complete request
javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:282)
at com.sun.proxy.$Proxy27.persist(Unknown Source)
at by.netcracker.artemyev.dao.GenericDao.add(GenericDao.java:35)
at by.netcracker.artemyev.service.GenericService.add(GenericService.java:24)
at by.netcracker.artemyev.service.impl.UserServiceImpl.addUser(UserServiceImpl.java:48)
at by.netcracker.artemyev.web.UserController.registrationUser(UserController.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1354)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)
Why I have this problem and how to fix it?
I resolved it by adding #Transactional annotation above the controller/service.
You have shown root-context.xml in your question but this context file doesn't have ViewResolver bean configuration. You must be having servlet context configuration file for Dispatcher Servlet (e.g. dispatcher-servlet.xml) configured in web.xml. Please add following configuration to your dispatcher-servlet.xml.
<tx:annotation-driven />
If you don't have xmlns:tx definition in your dispatcher-servlet.xml like other xmlns: definitions, then add it. Please make sure you have proper configuration for component-scan in dispacher servlet context.
<context:component-scan base-package="by.netcracker.artemyev.*" />
You can also refer to post #Transactional doesn't work in Spring Web MVC? where similar issue has been reported.
I encounter this issue when maintaining a legacy code, finally I realised from complex annotations.
it needs #EnableTransactionManagement on app level. otherwise #Transactional is not working

Spring MVC Service class NullPointerException [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trring to create an application where I am getting a problem. Here is the code
HomeController.java
#Controller
public class HomeController {
private EmployeeService employeeService;
#Autowired(required=true)
#Qualifier(value="employeeService")
public void setEmployeeService(EmployeeService employeeService)
{
this.employeeService = employeeService;
}
#RequestMapping("/index")
public ModelAndView indexWorld(#ModelAttribute("loginForm") Employee employee, ModelMap model) {
return new ModelAndView("index", "welcomeMessage","Hello Guest! welcome to our site");
}
#RequestMapping("/login")
public ModelAndView loginWorld(#ModelAttribute("loginForm") Employee employee, ModelMap model){
String result="", returnPage="";
if(this.employeeService.validateLogin(employee.getUsername(), employee.getPassword())){
result = "Welcome " + employee.getUsername();
returnPage = "home";
}
else{
result = "<BR>Login Failure";
returnPage = "index";
}
model.addAttribute("result", result);
return new ModelAndView(returnPage, model);
}
}
EmployeeServiceImpl.java
#Service
public class EmployeeServiceImpl implements EmployeeService {
/* (non-Javadoc)
* #see com.smart.service.EmployeeService#validateLogin(java.lang.String, java.lang.String)
*/
EmployeeDAO employeeDAO;
public void setEmployeeDAO(EmployeeDAO employeeDAO)
{
this.employeeDAO = employeeDAO;
}
#Override
public boolean validateLogin(String username, String password) {
// TODO Auto-generated method stub
return this.employeeDAO.validateLogin(username, password);
}
}
EmployeeDAOImpl.java
#Transactional(value="myTransactionManager")
public class EmployeeDaoImpl implements EmployeeDAO {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
#Override
public boolean validateLogin(String username, String password) {
return (long)this.sessionFactory.getCurrentSession().createQuery("SELECT COUNT(*) FROM EmployeeInfo WHERE username = :username AND password = :password")
.setString("username", username)
.setString("password", password).uniqueResult() > 0;
}
}
welcome-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"
xmlns:mvc="http://www.springframework.org/schema/mvc">
<context:annotation-config />
<context:component-scan base-package="com.smart" />
<mvc:annotation-driven />
<tx:annotation-driven transaction-manager="myTransactionManager" />
<bean id="employeeService" class="com.smart.service.EmployeeServiceImpl"></bean>
<bean id="employeeDAO" class="com.smart.dao.EmployeeDaoImpl"></bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="oracle.jdbc.OracleDriver"
p:url="jdbc:oracle:thin:#localhost:1521:IMS"
p:username="username"
p:password="password" />
<mvc:resources mapping="/resources/**" location="/resources/theme1/" />
</beans>
Error
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.lang.NullPointerException
com.smart.service.EmployeeServiceImpl.validateLogin(EmployeeServiceImpl.java:32)
com.smart.controller.HomeController.loginWorld(HomeController.java:38)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
I am getting in EmployeeServiceImpl.java on this line
return this.employeeDAO.validateLogin(username, password);
It seems I am getting null from validateLogin function although I am return value from validateLogin function. Why I am getting null?
EDIT
Now error
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myTransactionManager' is defined: No matching PlatformTransactionManager bean found for qualifier 'myTransactionManager' - neither qualifier match nor bean name match!
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myTransactionManager' is defined: No matching PlatformTransactionManager bean found for qualifier 'myTransactionManager' - neither qualifier match nor bean name match!
org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils.qualifiedBeanOfType(BeanFactoryAnnotationUtils.java:100)
org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils.qualifiedBeanOfType(BeanFactoryAnnotationUtils.java:56)
org.springframework.transaction.interceptor.TransactionAspectSupport.determineQualifiedTransactionManager(TransactionAspectSupport.java:377)
org.springframework.transaction.interceptor.TransactionAspectSupport.determineTransactionManager(TransactionAspectSupport.java:358)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:271)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy37.validateLogin(Unknown Source)
com.smart.service.EmployeeServiceImpl.validateLogin(EmployeeServiceImpl.java:33)
com.smart.controller.HomeController.loginWorld(HomeController.java:38)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
It seems EmployeeDAO is not being injected in EmployeeServiceImpl, wire EmployeeDAO using #Autowire or #Inject, Second EmployeeDAOImpl has not been declared a component (not sure if you have declared already in xml) so declare it with #Repository and also #Autowire SessionFactory. Hope this will do..
From the stacktrace it appears your code never calls validateLogin on the dao. The dao is null because there's nothing telling Spring to wire your DAO into your service. Add an #Autowired annotation to the setter in the service for the dao, similar to what you have in the controller wiring the service into it.

Spring Hibernate - NullPointerException SessionFactory

I got an error about SessionFactory.
CrudController.java
#Controller
public class CrudController {
#Autowired
private AlbumBo albumBo;
#RequestMapping(value = "/addAlbum")
#ResponseBody
public void addAlbum(
#RequestParam("NameRecordCompany") String nameRecordCompany,
#RequestParam("NameAlbum") String nameAlbum,
#RequestParam("YearName") String yearAlbum,
#RequestParam("NameArtist") String nameArtist,
#RequestParam("NameCategory") String nameCategory,
#RequestParam("SongList") String songList) throws JSONException {
Song temp = new Song();
ArrayList<Song> listaCanzoni = new ArrayList();
String songs = "{" + "\"songs\":" + songList + "}";
JSONObject jsonObjectSongList = new JSONObject(songs);
JSONArray jsonArraySongList = (JSONArray) jsonObjectSongList.get("songs");
for (int i = 0; i < jsonArraySongList.length(); i++) {
temp.setName((String) jsonArraySongList.getJSONObject(i).get("songName"));
temp.setDuration((String) jsonArraySongList.getJSONObject(i).get("songDuration"));
listaCanzoni.add(new Song(temp.getName(), temp.getDuration()));
}
Artist artist = new Artist(nameArtist);
Category category = new Category(nameCategory);
Album album = new Album(nameAlbum, yearAlbum);
album.setArtist(artist);
album.setCategory(category);
try {
albumBo.save(album); //line 67
JOptionPane.showMessageDialog(null, "albumDao.save(album) eseguita");
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
AlbumDaoImpl.java
public class AlbumDaoImpl implements AlbumDao {
#Autowired
SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory factory) {
this.sessionFactory = factory;
}
#Override
public void save(Album album) throws Exception {
Session session = sessionFactory.openSession(); //line 38
Transaction tx = null;
try {
tx = session.beginTransaction();
session.saveOrUpdate(album);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
} else {
e.printStackTrace();
}
} finally {
session.close();
}
}
}
AlbumBoImpl.java
public class AlbumBoImpl implements AlbumBo{
private AlbumDao albumDao;
static final Logger logger = Logger.getLogger(AlbumBoImpl.class);
public AlbumDao getAlbumDao() {
return albumDao;
}
public void setAlbumDao(AlbumDao albumDao) {
this.albumDao = albumDao;
}
#Override
public void save(Album album) throws Exception {
try{
albumDao.save(album); //line 35
}catch(Exception e){
logger.error(e);
throw e;
}
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
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.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>it.davidefruci.casadiscografica2.beans.Album</value>
<value>it.davidefruci.casadiscografica2.beans.Artist</value>
<value>it.davidefruci.casadiscografica2.beans.Song</value>
<value>it.davidefruci.casadiscografica2.beans.RecordCompany</value>
<value>it.davidefruci.casadiscografica2.beans.Category</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">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- DAO -->
<bean id="albumDao" class="it.davidefruci.casadiscografica2.daoImpl.AlbumDaoImpl"/>
<bean id="artistDao" class="it.davidefruci.casadiscografica2.daoImpl.ArtistDaoImpl"/>
<bean id="categoryDao" class="it.davidefruci.casadiscografica2.daoImpl.CategoryDaoImpl"/>
<bean id="recordCompanyDao" class="it.davidefruci.casadiscografica2.daoImpl.RecordCompanyDaoImpl"/>
<bean id="songDao" class="it.davidefruci.casadiscografica2.daoImpl.SongDaoImpl"/>
<!-- BO -->
<bean id="albumBo" class="it.davidefruci.casadiscografica2.boImpl.AlbumBoImpl">
<property name="albumDao" ref="albumDao"></property>
</bean>
<bean id="artistBo" class="it.davidefruci.casadiscografica2.boImpl.ArtistBoImpl">
<property name="artistDao" ref="artistDao"></property>
</bean>
<bean id="categoryBo" class="it.davidefruci.casadiscografica2.boImpl.CategoryBoImpl">
<property name="categoryDao" ref="categoryDao"></property>
</bean>
<bean id="recordCompanyBo" class="it.davidefruci.casadiscografica2.boImpl.RecordCompanyBoImpl">
<property name="recordCompanyDao" ref="recordCompanyDao"></property>
</bean>
<bean id="songBo" class="it.davidefruci.casadiscografica2.boImpl.SongBoImpl">
<property name="songDao" ref="songDao"></property>
</bean>
I have a JSP where I add the datas that I want to save into my db.
When I click on the submit button, an Ajax call is invoked. This call invokes the CrudController, who should save data on my db with addAlbum method.
When the CrudController is invoked Tomcat tells me:
java.lang.NullPointerException
at it.davidefruci.casadiscografica2.daoImpl.AlbumDaoImpl.save(AlbumDaoImpl.java:38)
at it.davidefruci.casadiscografica2.boImpl.AlbumBoImpl.save(AlbumBoImpl.java:35)
at it.davidefruci.casadiscografica2.controllers.CrudController.addAlbum(CrudController.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
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:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
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)
I wrong something with the sessionFactory initialization?
<bean id="personDao"class="com.studytrails.tutorials.springhibernatesessionfactory.PersonDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
You will need to inject session factory in DAO you are using which will help you do CRUD operations on your Object either you can configure this in XML or using annotation.
Also please help your self by going through the given like below
Example of spring hibernate integration
Two things you can do, one is change to inject the SessionFactory to Dao by yourself.
<!-- DAO -->
<bean id="albumDao" class="it.davidefruci.casadiscografica2.daoImpl.AlbumDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
You can do this for all DAOs.
Or
put a component scan on the applicationContext.xml XML configuration so that the SessionFactory will get Autowired.
<context:component-scan base-package="it.davidefruci.casadiscografica2"/>

Using hibernate.c3p0 when creating a EntityManagerFactoryBean in Java

I recently moved from the .Net world to the Java world.
I have build a core project which is to be used by multiple clients (web client, api, ...)
Doing so i got tired of having to configure my data access beans and connection strings in multiple projects. The goal is to include my "core-project.jar" and be able to use that without having to configure data access beans and connection strings.
I found this: (seems to have trouble with the webserver atm.)
http://www.baeldung.com/2011/12/13/the-persistence-layer-with-spring-3-1-and-jpa/
which resulted in this code which works and completes my goal.
BaseRepository
package com.company.core.data.repositories;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
public abstract class BaseRepository {
protected EntityManagerFactory emf;
#PersistenceUnit
public void setEntityManagerFactory(EntityManagerFactory emf) {
this.emf = emf;
}
}
UserRepository
package com.company.core.data.repositories;
import com.company.core.data.interfaces.IUserRepository;
import com.company.core.data.pojos.UserPojo;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import java.util.List;
#Component
public class UserRepository extends BaseRepository implements IUserRepository {
public UserPojo getByEmail(String email) throws Exception {
EntityManager em = emf.createEntityManager();
List<UserPojo> results = em.createQuery("FROM UserPojo u WHERE u.email = ?", UserPojo.class)
.setParameter(1, email)
.getResultList();
em.close();
return firstOrDefault(results);
}
public static <T> T firstOrDefault(List<T> list){
if(list.size() > 0)
return list.get(0);
return null;
}
}
UserPojo
package com.company.core.data.pojos;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table( name = "User" )
public class UserPojo {
// ALL THE Properties
}
EntityManagerFactoryConfiguration
package com.company.core.configuration;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
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.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#ComponentScan({"com.company.core.data"})
public class EntityManagerFactoryConfiguration {
public EntityManagerFactoryConfiguration() {
super();
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[]{"com.company.core.data.pojos"});
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
hibernateProperties.setProperty("hibernate.show_sql", "false");
// hibernateProperties.setProperty("hibernate.connection.provider_class", "org.hibernate.connection.C3P0ConnectionProvider");
// hibernateProperties.setProperty("hibernate.c3p0.max_size", "100");
// hibernateProperties.setProperty("hibernate.c3p0.min_size", "0");
// hibernateProperties.setProperty("hibernate.c3p0.acquire_increment", "1");
// hibernateProperties.setProperty("hibernate.c3p0.idle_test_period", "200");
// hibernateProperties.setProperty("hibernate.c3p0.max_statements", "0");
// hibernateProperties.setProperty("hibernate.c3p0.timeout", "300");
em.setJpaProperties(hibernateProperties);
return em;
}
#Bean
public DataSource dataSource() {
final org.springframework.jdbc.datasource.DriverManagerDataSource dataSource = new org.springframework.jdbc.datasource.DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1/databasename?autoReconnect=true");
dataSource.setUsername("user");
dataSource.setPassword("password");
return dataSource;
}
#Bean
public DataSource c3p0dataSource() {
final com.mchange.v2.c3p0.DriverManagerDataSource dataSource = new com.mchange.v2.c3p0.DriverManagerDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1/databasename?autoReconnect=true");
dataSource.setUser("user");
dataSource.setPassword("password");
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
As you can i want to use hibernate.c3p0 for connection management.
commenting in the outcommented hibernateproperties results in:
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1771)
at org.hibernate.jpa.internal.TransactionImpl.begin(TransactionImpl.java:64)
at com.company.core.data.repositories.UserRepository.getByEmail(UserRepository.java:30)
at com.company.core.business.implementations.UserService.getByEmail(UserService.java:18)
at com.company.api.UserController.getByEmail(UserController.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
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.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:362)
at org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:60)
at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:138)
at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1183)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1020)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:283)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2463)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2452)
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: org.hibernate.exception.GenericJDBCException: Could not open connection
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:235)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:162)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1435)
at org.hibernate.jpa.internal.TransactionImpl.begin(TransactionImpl.java:61)
... 50 more
Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database!
at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:689)
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)
at org.hibernate.c3p0.internal.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:90)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228)
... 55 more
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1418)
at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:606)
at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:526)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:755)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:682)
... 59 more
i have also tried to create a c3p0 datesource (see method c3p0dataSource()9 with no luck either.
I think i might be in over my head, any guidance would be appreciated!!
The xml configuration:
application-context.xml
<beans:bean id="emf" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<beans:property name="persistenceUnitName" value="DataSource"/>
</beans:bean>
persistence.xml
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="DataSource">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1/database?autoReconnect=true" />
<property name="javax.persistence.jdbc.user" value="user" />
<property name="javax.persistence.jdbc.password" value="password" />
<!-- Important -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" />
<property name="hibernate.c3p0.max_size" value="100" />
<property name="hibernate.c3p0.min_size" value="0" />
<property name="hibernate.c3p0.acquire_increment" value="1" />
<property name="hibernate.c3p0.idle_test_period" value="300" />
<property name="hibernate.c3p0.max_statements" value="0" />
<property name="hibernate.c3p0.timeout" value="100" />
</properties>
</persistence-unit>
</persistence>

Spring. AutoWired object NullPointerException [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 9 years ago.
I have two classes.
CustomUserDetailsService - Works fine!
#Service
#Transactional(readOnly = true)
#SuppressWarnings("unused")
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserDAO userDAO;
#Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
return userDAO.getUser(login);
}
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
}
RegistrationServiceImpl - Throws NullPointerException on userDAO.addUser(newUser); method call.
#Service
#Transactional(readOnly = false)
public class RegistrationServiceImpl implements RegistrationService {
#Autowired
private UserDAO userDAO;
#Override
public void registerUser(Registration reg) {
User newUser = new User();
newUser.setUsername(reg.getUsername());
newUser.setPassword(reg.getPassword());
newUser.setFirstName(reg.getFirstName());
newUser.setLastName(reg.getLastName());
userDAO.addUser(newUser);
}
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
}
mvc-dispatcher-servlet.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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.petrez" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/Library" />
<property name="username" value="root" />
<property name="password" value="G190419g" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan" value="com.petrez" />
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="show_sql">false</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.petrez.model.User</value>
<value>com.petrez.model.Role</value>
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="userDAO" class="com.petrez.dao.UserDAOImpl" />
<bean id="roleDAO" class="com.petrez.dao.RoleDAOImpl" />
<bean id="userDetailsService" class="com.petrez.service.CustomUserDetailsService" />
<bean id="registrationService" class="com.petrez.service.RegistrationServiceImpl" />
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
Can anyone say me, why?
Thanks!
UPD
Stack Trace:
Nov 08, 2013 11:04:33 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.petrez.service.RegistrationServiceImpl.registerUser(RegistrationServiceImpl.java:28)
at com.petrez.controller.RegistrationPage.processRegistration(RegistrationPage.java:23)
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:601)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
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:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
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:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
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:722)
RegistrationPage
#Controller
#RequestMapping(value = "/registration")
#SuppressWarnings("unused")
public class RegistrationPage {
#RequestMapping(method = RequestMethod.POST)
public String processRegistration(#ModelAttribute("reg") Registration reg, BindingResult result) {
if(result.hasErrors()) {
return "/?error=true";
}
else {
new RegistrationServiceImpl().registerUser(reg);
return "success-login";
}
}
}
You're manually instantiating the RegistrationServiceImpl instead of retrieving the Spring-managed bean from the context. Inject the RegistrationService into your RegistrationPage.
You missed <context:annotation-config/> in your configuration
Add <context:annotation-config/> or <context:component-scan base-package="org.example"/>
to top of your mvc-dispatcher-servlet.xml configuration file.
eg
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:component-scan base-package="org.example"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp" />
</bean>
</beans>

Categories