I had Spring Data's repository working in a #Controller a short while ago. Having moved data access down into a #Service, it stopped working. Everything looks fine to me.... Why is this DI failing?
Here's my spring-config:
<?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:data="http://www.springframework.org/schema/data/jpa"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="POSTGRESQL" />
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/cp" />
<property name="username" value="cp_user" />
<property name="password" value="+JMJ+pw0m2d" />
</bean>
<data:repositories base-package="com.mydomain.data.repository" />
<mvc:annotation-driven />
</beans>
My application:
#ComponentScan
#EnableAutoConfiguration
#ImportResource("classpath:spring-config.xml")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
My controller:
#Controller
#RequestMapping("/app/user")
#ExposesResourceFor(User.class)
public class UserController {
#RequestMapping(value = "/{userid}", method = RequestMethod.GET, produces = "application/json")
#ResponseBody
public HttpEntity<UserResource> get(#PathVariable("userid") long id) {
ProfileService ps = new ProfileService();
UserResource resource = ps.get(id);
return new ResponseEntity<UserResource>(resource, HttpStatus.OK);
}
}
And my service:
#Service
#ExposesResourceFor(User.class)
public class ProfileService {
#Inject
private UserRepository users;
public UserResource get(long id) {
Long longId = new Long(id);
User user = users.findOne(longId); // Line 24
if (user == null) {
throw new ResourceNotFoundException();
}
UserMapper assembler = new UserMapper();
UserResource resource = assembler.toResource(user);
return resource;
}
public void update(UserResource resource) {
UserMapper assembler = new UserMapper();
User user = assembler.toEntity(resource);
users.save(user);
}
}
Throwing exception:
java.lang.NullPointerException
com.mydomain.service.ProfileService.get(ProfileService.java:24)
com.mydomain.app.web.UserController.get(UserController.java:74)
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:214)
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:748)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:947)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:878)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:946)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:822)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
Where ProfileService:24 is:
User user = users.findOne(longId);
In your controller you create ProfileService instance with a new keyword and it is not managed by Spring (Spring doesn't know about it and cannot inject UserRepository - this causes NullPointerException). You have to inject ProfileService into UserController the same way you inject UserRepository into ProfileService. For example:
#Controller
#RequestMapping("/app/user")
#ExposesResourceFor(User.class)
public class UserController {
#Autowired
private ProfileService profileService;
#RequestMapping(value = "/{userid}", method = RequestMethod.GET, produces = "application/json")
#ResponseBody
public HttpEntity<UserResource> get(#PathVariable("userid") long id) {
UserResource resource = profileService.get(id);
return new ResponseEntity<UserResource>(resource, HttpStatus.OK);
}
}
Related
I have been getting this error after generating the User class from database, everything seems to be in order in the User.hbm.xml yet I can't find why it's not mapped!
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/CCTVDATASET] threw exception [Request processing failed; nested exception is org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [from User]] with root cause
org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:189)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:109)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:95)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:331)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3633)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3522)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:706)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:562)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:190)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
at com.journaldev.spring.dao.UserDAOImpl.listUsers(UserDAOImpl.java:42)
at com.journaldev.spring.service.UserServiceImpl.listUsers(UserServiceImpl.java:35)
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:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy28.listUsers(Unknown Source)
at com.journaldev.spring.UserController.listUsers(UserController.java:31)
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.invoke(InvocableHandlerMethod.java:215)
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:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
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:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:500)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)
User.java
// default package
// Generated Nov 6, 2017 9:57:34 AM by Hibernate Tools 5.2.3.Final
package com.journaldev.spring.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* User generated by hbm2java
*/
public class User implements java.io.Serializable {
private Integer iduser;
private String username;
private String password;
private Integer ssoId;
private Set logs = new HashSet(0);
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public User(String username, String password, Integer ssoId, Set logs) {
this.username = username;
this.password = password;
this.ssoId = ssoId;
this.logs = logs;
}
public Integer getIduser() {
return this.iduser;
}
public void setIduser(Integer iduser) {
this.iduser = iduser;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getSsoId() {
return this.ssoId;
}
public void setSsoId(Integer ssoId) {
this.ssoId = ssoId;
}
public Set getLogs() {
return this.logs;
}
public void setLogs(Set logs) {
this.logs = logs;
}
}
User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Nov 6, 2017 9:57:34 AM by Hibernate Tools 5.2.3.Final -->
<hibernate-mapping>
<class catalog="testdb" entity-name="User" name="User" table="user">
<id name="iduser" type="java.lang.Integer">
<column name="iduser"/>
<generator class="identity"/>
</id>
<property generated="never" lazy="false" name="username" type="string">
<column length="45" name="username" not-null="true"/>
</property>
<property generated="never" lazy="false" name="password" type="string">
<column length="45" name="password" not-null="true"/>
</property>
<property generated="never" lazy="false" name="ssoId" type="java.lang.Integer">
<column name="SSO_ID"/>
</property>
<set fetch="select" inverse="true" lazy="true" name="logs"
sort="unsorted" table="log">
<key>
<column name="iduser" not-null="true"/>
</key>
<one-to-many class="Log"/>
</set>
</class>
</hibernate-mapping>
UserDAO.java
package com.journaldev.spring.dao;
import java.util.List;
import com.journaldev.spring.model.User;
public interface UserDAO {
public void addUser(User u);
public void updateUser(User u);
public List<User> listUsers();
public User getUserById(int id);
public void removeUser(int id);
}
UserDAOImpl.java
package com.journaldev.spring.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import com.journaldev.spring.model.User;
#Repository
public class UserDAOImpl implements UserDAO {
private static final Logger logger = LoggerFactory.getLogger(UserDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void addUser(User u) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(u);
logger.info("User saved successfully, User Details="+u);
}
#Override
public void updateUser(User u) {
Session session = this.sessionFactory.getCurrentSession();
session.update(u);
logger.info("User updated successfully, User Details="+u);
}
#SuppressWarnings("unchecked")
#Override
public List<User> listUsers() {
Session session = this.sessionFactory.getCurrentSession();
List<User> usersList = session.createQuery("from User").list();
for(User u : usersList){
logger.info("User List::"+u);
}
return usersList;
}
#Override
public User getUserById(int id) {
Session session = this.sessionFactory.getCurrentSession();
User u = (User) session.load(User.class, new Integer(id));
logger.info("User loaded successfully, User details="+u);
return u;
}
#Override
public void removeUser(int id) {
Session session = this.sessionFactory.getCurrentSession();
User u = (User) session.load(User.class, new Integer(id));
if(null != u){
session.delete(u);
}
logger.info("User deleted successfully, user details="+u);
}
}
UserService.java
package com.journaldev.spring.service;
import java.util.List;
import com.journaldev.spring.model.User;
public interface UserService {
public void addUser(User u);
public void updateUser(User u);
public List<User> listUsers();
public User getUserById(int id);
public void removeUser(int id);
}
UserServiceImpl.java
package com.journaldev.spring.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.journaldev.spring.dao.UserDAO;
import com.journaldev.spring.model.User;
#Service
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
#Override
#Transactional
public void addUser(User u) {
this.userDAO.addUser(u);
}
#Override
#Transactional
public void updateUser(User u) {
this.userDAO.updateUser(u);
}
#Override
#Transactional
public List<User> listUsers() {
return this.userDAO.listUsers();
}
#Override
#Transactional
public User getUserById(int id) {
return this.userDAO.getUserById(id);
}
#Override
#Transactional
public void removeUser(int id) {
this.userDAO.removeUser(id);
}
}
UserController.java
package com.journaldev.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.journaldev.spring.service.UserService;
import com.journaldev.spring.model.User;
#Controller
public class UserController {
private UserService userService;
#Autowired(required=true)
#Qualifier(value="userService")
public void setUserervice(UserService us){
this.userService = us;
}
#RequestMapping(value = "/cctvsets", method = RequestMethod.GET)
public String listUsers(Model model) {
System.out.println("CHECKPOINT 1");
model.addAttribute("user", new User());
System.out.println("CHECKPOINT 2");
model.addAttribute("listUsers", this.userService.listUsers());
System.out.println("CHECKPOINT 3");
return "cctvsets";
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
</session-factory>
</hibernate-configuration>
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-4.0.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 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/testdb" />
<beans:property name="username" value="root" />
<beans:property name="password" value="root" />
</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>com.journaldev.spring.model.Person</beans:value>
<beans:value>com.journaldev.spring.model.User</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:bean>
<beans:bean id="personDAO" class="com.journaldev.spring.dao.PersonDAOImpl">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="personService" class="com.journaldev.spring.service.PersonServiceImpl">
<beans:property name="personDAO" ref="personDAO"></beans:property>
</beans:bean>
<beans:bean id="userDAO" class="com.journaldev.spring.dao.UserDAOImpl">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="userService" class="com.journaldev.spring.service.UserServiceImpl">
<beans:property name="userDAO" ref="userDAO"></beans:property>
</beans:bean>
<context:component-scan base-package="com.journaldev.spring" />
<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>
You must mapped the User.hbm.xml in your Hibernate.cfg.xml.
User is a reserved work in mysql. Rename your table to e.g: 'SystemUser' or whatever you like, which is not a reserved keyword in mysql.
I understand that it is possible to configure a Spring application without the use of XML config files, and have commited to this method. I am not sure, however, how to declare HTTP interceptors in this manner. I am using this tutorial, which declares the following XML.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/welcome.htm">welcomeController</prop>
</props>
</property>
<property name="interceptors">
<list>
<ref bean="maintenanceInterceptor" />
<ref bean="executeTimeInterceptor" />
</list>
</property>
</bean>
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name="interceptors">
<list>
<ref bean="executeTimeInterceptor" />
</list>
</property>
</bean>
<bean id="welcomeController"
class="com.mkyong.common.controller.WelcomeController" />
<bean class="com.mkyong.common.controller.MaintenanceController" />
<bean id="executeTimeInterceptor"
class="com.mkyong.common.interceptor.ExecuteTimeInterceptor" />
<bean id="maintenanceInterceptor"
class="com.mkyong.common.interceptor.MaintenanceInterceptor">
<property name="maintenanceStartTime" value="23" />
<property name="maintenanceEndTime" value="24" />
<property name="maintenanceMapping" value="/SpringMVC/maintenance.htm" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
How to do this in Java? There is no #Interceptor annotation.
SpringApplication.java
#SuppressWarnings("WeakerAccess")
#SpringBootApplication
#PropertySources(value = {#PropertySource("classpath:/application.properties")})
public class SpringbackendApplication {
#Autowired
Environment env;
public static void main(String[] args) {
SpringApplication.run(SpringbackendApplication.class, args);
initializeFirebase();
}
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public UserController userController() {
UserController userController = new UserController(getUserDAO(), getYodleeDAO());
userController.setCobrandSession(cobrandSession());
userController.setUserSessionManager(userSessionManager());
userController.setAccountsService(accountsService());
userController.setTransactionsService(transactionsService());
return userController;
}
#Bean
public TestController testController() {
TestController testController = new TestController();
testController.setCobrandSession(cobrandSession());
testController.setUserSessionManager(userSessionManager());
testController.setAccountsService(accountsService());
testController.setTransactionsService(transactionsService());
return testController;
}
#Bean
public CobrandSession cobrandSession() {
CobrandSession cobrandSession = new CobrandSession();
cobrandSession.setApiBase(this.env.getProperty("API_BASE"));
cobrandSession.setLogin(this.env.getProperty("LOGIN"));
cobrandSession.setPassword(this.env.getProperty("PASSWORD"));
cobrandSession.setLocale(this.env.getProperty("LOCALE"));
cobrandSession.setRestTemplate(restTemplate());
cobrandSession.setGson(gson());
return cobrandSession;
}
#Bean
public AccountsService accountsService() {
AccountsService accountsService = new AccountsService();
accountsService.setApiBase(this.env.getProperty("API_BASE"));
accountsService.setRestTemplate(restTemplate());
accountsService.setGson(gson());
return accountsService;
}
#Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setOutputStreaming(false); // If we don't turn this off, we may get HttpRetryException on 401's.
return new RestTemplate(factory);
}
#Bean
public Gson gson() {
return new Gson();
}
}
To move your Spring beans defined in an XML file to a Configuration class (marked with #Configuration) you would need something like this:
#Configuration
public class MyConfig {
#Bean(name="executeTimeInterceptor")
public ExecuteTimeInterceptor getExecuteTimeInterceptor() {
return new com.mkyong.common.interceptor.ExecuteTimeInterceptor();
}
#Bean(name="maintenanceInterceptor")
public MaintenanceInterceptor getMaintenanceInterceptor(#Value("${properties.maintenanceStartTime}") int maintenanceStartTime,
#Value("${properties.maintenanceEndTime}") int maintenanceEndTime,
#Value("${properties.maintenanceMapping}") String maintenanceMapping) {
MaintenanceInterceptor myInt = new MaintenanceInterceptor();
myInt.setMaintenanceStartTime(maintenanceStartTime);
myInt.setmMaintenanceEndTime(maintenanceEndTime);
myInt.setMaintenanceMapping(maintenanceMapping);
return myInt;
}
}
...then in some propertiesFile.properties on the classpath add these...
properties.maintenanceStartTime=23
properties.maintenanceEndTime=24
properties.maintenanceMapping=/SpringMVC/maintenance.htm
EDIT
I see you are getting your props from the Environment, so instead of #Value injection, use the way you have it in your code right now.
You have to override WebMvcConfigurerAdapter.addInterceptors() method and add your interceptors:
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CustomInterceptor());
}
Don't forget to mark your class with #Configuration
This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 6 years ago.
Its the First time i am integrating spring with hibernate, When i
invoke any method of Dao class i am getting null pointer Exception
I am using abstract factory pattern Source code of Abstract class :
public abstract class Content {
#Autowired
HibernateOperations ho;
#Transactional
public List<ContentDes> getContentDes(String sql,int limit){
//do it with autowired
List<Object[]> ls = new ArrayList<Object[]>();
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
System.out.println("--before invoking method---");
ho.just_print();
ls = ho.getResultListByLimit(sql,limit);
for(Object[] obj: ls){
ContentDes contentDes = new ContentDes();
contentDes.setCode((String)obj[0]);
contentDes.setContent_prv((String)obj[1]);
contentDes.setPricetag((String)obj[2]);
contentDes_ls.add(contentDes);
}
return contentDes_ls;
}
abstract List<ContentDes> getRandomContent(int limit);
//abstract List<ContentDes> getDistinctCat();
}
And i have five class that are extending my Content Class: coding of
one of my child id liem below:
public class Wallpaper extends Content{
#Override
public List<ContentDes> getRandomContent(int limit) {
String sql = "select code,prv,pricetag from Wallpaper where cat not like 'Holy Deities' order by rand() limit "+limit+"";
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
contentDes_ls = getContentDes(sql,limit);
return contentDes_ls;
}
}
And class which returning clasess obects according to the content type
is :
public class GetContentFactory {
//use getContent method to get object of type Content
public Content getContent(String contentType) {
contentType = contentType.toLowerCase();
if (contentType.equalsIgnoreCase("wallpaper")) {
return new Wallpaper();
} else if (contentType.equalsIgnoreCase("animation")) {
return new Animation();
} else if (contentType.equalsIgnoreCase("ringtone")) {
return new Ringtone();
} else if (contentType.equalsIgnoreCase("video")) {
return new Video();
}
else if (contentType.equalsIgnoreCase("game")) {
return new Game();
}
else {
System.out.println(" unknow request in GetContentFactory class");
}
return null;
}
}//end of GetContentFactory class.
My main class is :
public class GetContent {
GetContentFactory contentFactory = new GetContentFactory();
}
public List<ContentDes> getRandomContent(String content_type, int limit) {
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
Content con = contentFactory.getContent(content_type);
contentDes_ls = con.getRandomContent(limit);
for (ContentDes contentDes : contentDes_ls) {
System.out.println("prv----"+contentDes.getContent_prv());
}
return contentDes_ls;
}
}
Code of my dao class is :
#Repository
public class HibernateOperations {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
//pass the sql query to get result for multiple column
public List<Object[]> getResultListByLimit(String query,int limit){
System.out.println("in get result-------");
Session session = this.sessionFactory.getCurrentSession();
List<Object[]> ls_ob = new ArrayList<Object[]>();
Query q = session.createQuery(query);
q.setMaxResults(limit);
ls_ob = (List<Object[]>)q.list();
return ls_ob;
}
public List<Object> getListForSingleColumn(String query){
Session session = this.sessionFactory.getCurrentSession();
List<Object> ls_ob = new ArrayList<Object>();
Query q = session.createQuery(query);
ls_ob = q.list();
return ls_ob;
}
public void SaveObject(Object obj){
Session session = this.sessionFactory.getCurrentSession();
List<Object[]> ls_ob = new ArrayList<Object[]>();
session.save(obj);
}
public void just_print(){
System.out.println("---------in method hibenate operation------");
}
}
when My controller class methods call:
GetContent gc = new GetContent();
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
contentDes_ls = gc.getRandomContent("wallpaper", 3);
i got an exception:
its prints the
--before invoking method---(its is the sout of my content class method Name "getContentDes")
Apr 25, 2016 6:03:04 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [DefaultServlet] in context with path [/slwap_sh] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at lanka.content.get.Content.getContentDes(Content.java:37)
at lanka.content.get.Wallpaper.getRandomContent(Wallpaper.java:45)
at lanka.content.controller.ContentController.sriWap(ContentController.java:65)
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:222)
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.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
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:969)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
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: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:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
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)
I am unable to call any of my Dao Class methods i got null pointer
when i called any method of my Dao(HibernateOperations.java) Class
Can anyone please help me to find out my mistake
coding of DefaultServlet-servlet.xml is like below:
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<mvc:annotation-driven />
<mvc:annotation-driven enable-matrix-variables="true" />
<context:component-scan base-package="lanka.content.controller" />
<context:component-scan base-package="lanka.content.domain" />
<context:component-scan base-package="lanka.content.utility" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- start of languages xml code -->
<!-- lang param is defined in the mvc interceptor -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="WEB-INF/propFiles/content" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<!-- end of languages xml code -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptor>
<!-- <mvc:interceptor>
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/resources/**"/>
<bean id="storingWapHits"
class="vodafone.interceptor.StroringHits">
</bean>
</mvc:interceptor> -->
</mvc:interceptors>
<mvc:resources mapping="/resources/**" location="/resources/design/" />
<!-- start of hibernate integration -->
<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/wapsite" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<!-- hibernate4AnnotatedSessionFactory is a session fectory-->
<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>lanka.content.table.Game</value>
<value>lanka.content.table.Scrsaver</value>
<value>lanka.content.table.Video</value>
<value>lanka.content.table.Wallpaper</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>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
<!-- <bean id="personService" class="com.journaldev.spring.service.PersonServiceImpl">
<property name="personDAO" ref="personDAO"></property>
</bean>-->
<bean id="HibernateOperations" class="lanka.content.utility.HibernateOperations">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
</beans>
By doing :
new Wallpaper();
You are not letting spring do his work, that is to say inject things in your objects :
#Autowired
HibernateOperations ho;
ho will always be null.
Every Content subclasses should be spring beans, and you have to get rid of your GetContentFactory, and only autowire every single spring bean
EDIT : Abstract Factory Design
Define your beans like this :
#Component
#Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Wallpaper extends Content {
Declare the GetContentFactory as a spring bean as well :
#Component
public class GetContentFactory {
#Autowired
private Wallpaper wallpaper;
This has to be avoided as well :
GetContentFactory contentFactory = new GetContentFactory();
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
So I have little problem. I can't add informations to database because I get an error:
HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException
Here is my controller:
package pl.edu.controller;
#Controller
public class StudentAdmissionController {
#RequestMapping(value = "/admissionForm.html", method = RequestMethod.GET)
public ModelAndView getAdmissionForm() {
ModelAndView model = new ModelAndView("AdmissionForm");
return model;
}
#RequestMapping(value = "/submitAdmissionForm.html", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(#RequestParam("pojemnosc") float pojemnosc,
#RequestParam("modelSamochodu") String modelSamochodu, #RequestParam("liczbaPasazerow") int liczbaPasazerow,
#RequestParam("liczbaDrzwi") int liczbaDrzwi) {
ModelAndView model = new ModelAndView("AdmissionSuccess");
Silnik silnik = new Silnik();
silnik.setPojemnosc(pojemnosc);
silnik.setId(1);
Samochod samochod = new Samochod();
samochod.setSilnik(silnik);
samochod.setLiczbaDrzwi(liczbaDrzwi);
samochod.setLiczbaPasazerow(liczbaPasazerow);
samochod.setModel(modelSamochodu);
samochod.setLiczbaPoduszek(liczbaPasazerow * 2);
samochod.setId(1);
model.addObject("msg",
"Details submited by you: Pojemnosc: " + silnik.getPojemnosc() + " Model: " + samochod.getModel()
+ ", Liczba drzwi: " + samochod.getLiczbaDrzwi() + ", Liczba pasazerow: "
+ samochod.getLiczbaPasazerow() + ", Liczba poduszek: " + samochod.getLiczbaPoduszek());
SamochodDao samochodDao = new SamochodDao();
samochodDao.dodaj(samochod);
return model;
}
}
My SamochodDao class:
public class SamochodDao {
private JdbcTemplate jdbcTemplate;
#Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
#Transactional
public void dodaj(final Samochod samochod) {
final String engineQuery = "insert into silnik (pojemnosc) values (?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(engineQuery, new String[] { "id" });
ps.setFloat(1, samochod.getSilnik().getPojemnosc());
return ps;
}
}, keyHolder);
String carQuery = "insert into samochod (id, silnik,model,liczbaDrzwi,liczbaPasazerow,liczbaPoduszek) values (?,?,?,?,?,?)";
Object[] inputs = new Object[] { keyHolder.getKey(), keyHolder.getKey(), samochod.getModel(),
samochod.getLiczbaDrzwi(), samochod.getLiczbaPasazerow(), samochod.getLiczbaPoduszek() };
jdbcTemplate.update(carQuery, inputs);
}
public void usun(int id) {
String query = "DELETE FROM samochod WHERE id = ?";
Object[] inputs = new Object[] { id };
jdbcTemplate.update(query, inputs);
query = "DELETE FROM silnik WHERE id = ?";
jdbcTemplate.update(query, inputs);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
public List<Samochod> listuj() {
String sql = "SELECT * FROM Silnik";
List<Silnik> listaSilnikow = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Silnik.class));
List<Samochod> listaSamochodow = new ArrayList();
for (Silnik silnik : listaSilnikow) {
sql = "SELECT * FROM samochod WHERE id = ?";
Samochod samochod = (Samochod) jdbcTemplate.queryForObject(sql, new Object[] { silnik.getId() },
new SamochodRowMapper());
samochod.setSilnik(silnik);
listaSamochodow.add(samochod);
}
return listaSamochodow;
}
}
And my servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="pl.edu" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
</beans>
And when I'm trying to add new "Samochod" to database I have error:
HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
pl.edu.dao.SamochodDao.dodaj(SamochodDao.java:26)
pl.edu.controller.StudentAdmissionController.submitAdmissionForm(StudentAdmissionController.java:48)
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:497)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Somebody have maybe any idea what I'm doing wrong?
#edit
Line 26 from SamochodDao:
jdbcTemplate.update(new PreparedStatementCreator() {
#edit2
Btw. When I'm running this code as test, it works ok. Here are my beans from normal application:
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd ">
<aop:aspectj-autoproxy />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="Silnik" class="pl.edu.lab1.Silnik">
<property name="pojemnosc" value="1.4"></property>
<property name="id" value="1"></property>
</bean>
<bean id="Samochod" class="pl.edu.lab1.Samochod">
<property name="silnik" ref="Silnik"></property>
<property name="model" value="Audi"></property>
<property name="liczbaPasazerow" value="2"></property>
<property name="liczbaDrzwi" value="4"></property>
<property name="liczbaPoduszek" value="2"></property>
<property name="id" value="1"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="SamochodDao" class="pl.edu.dao.SamochodDao">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
But when I change it to web-app I have errors.
It looks like jdbcTemplate is nullValue because it is created in controller.
Try to create Dao instance once in context and autowired into controller.
I'm working on a project using Struts, Spring and Hibernate. After clicking on a button, the Struts action leads me through a DS and DAO, in which I try to call a native query to update the DB. Here is the error trace:
javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.hibernate.ejb.QueryImpl.executeUpdate(QueryImpl.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:79)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:618)
at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:310)
at $Proxy496.executeUpdate(Unknown Source)
at com.my.project.MyDAO.unsubscribe(MyDAO.java:307)
at com.my.project.MyDS.unsubscribe(MyDS.java:507)
at com.my.project.MyDS.updateValue(MyDS.java:784)
at com.my.project.MyAction.handleUpdate(MyAction.java:235)
MyDAO :
public class MyDAO extends
AbstractDAOGenericImpl<MyEntity> {
/** Entity Manager */
#PersistenceContext(unitName = "myPersistenceUnit")
private EntityManager entityManager;
#Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public int unsubscribe(String entityId) throws JrafDaoException {
StringBuilder strQuery = new StringBuilder();
strQuery.append("update MYENTITY set SUBSCRIBE=:subscribe where ENTITY_ID=:entity_id");
final Query myQuery = getEntityManager().createNativeQuery(strQuery.toString(), MyEntity.class);
myQuery.setParameter("subscribe", "N");
myQuery.setParameter("entity_id", entityId);
try {
return myQuery.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
In MyDS :
#Autowired
#Qualifier("MyDAO")
private MyDAO myDao;
#Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public int unsubscribe(String entityId) throws JrafDomainException {
return myDao.unsubscribe(entityId);
}
MyAction :
public class MyAction extends DispatchAction {
private MyDS myDS;
// ...
private ActionForward handleUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
MyForm myForm = (MyForm) form;
myDS.unsubscribe(myForm.getEntityId());
}
}
And application-context-spring.xml :
<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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
<!-- Enterprise layer's dependencies -->
<bean id="springLocator"
class="com.jraf.bootstrap.locator.SpringLocator">
</bean>
<!-- To precise the persistence configuration name file -->
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>/META-INF/persistence-web.xml</value>
</list>
</property>
</bean>
<!-- EntityManagerFactory definition : JPA one -->
<bean id="myEmf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager"
ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="myPersistenceUnit" />
</bean>
<!-- TransactionManager JPA one -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf" />
</bean>
<!-- EntityManagerFactory definition : JPA one -->
<bean id="myEmf2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="myPersistenceUnit2" />
</bean>
<!-- Transaction Manager definition : JPA one-->
<bean id="myTxManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf2" />
</bean>
<!-- Enable annotation usage for transaction -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="1" />
<property name="maxPoolSize" value="1" />
<property name="queueCapacity" value="1" />
</bean>
<bean id="myDS" class="com.my.internal.MyDS">
<property name="myDao" ref="MyDAO"/>
</bean>
<!-- Enable the annotation usage (bean injection for instance) -->
<context:annotation-config />
</beans>
I'm working on an existing project which is why the unsubscribe function already exists and uses a native query instead of a HQL one. But maybe I should use it instead...?
Thanks for your help.
I also faced the similar issue.
Adding
tx:annotation-driven transaction-manager="transactionManager"
to your spring context xml will resolve the issue.