I am getting the below error while trying to call a service class
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.NullPointerException
org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:431)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:372)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:417)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:255)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
com.plm.conn.model.QueueService$$EnhancerBySpringCGLIB$$9405c9f4.getAll()
com.plm.conn.hcontroller.HomeController.home(HomeController.java:67)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:685)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
My servlet-context.xml
<!-- Derby configuration -->
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName"
value="org.apache.derby.jdbc.ClientDriver" />
<beans:property name="url"
value="jdbc:derby://localhost:1527//office;create=false" />
<beans:property name="username" value="office" />
</beans:bean>
<!-- EntityManagerFactory -->
<beans:bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="jtaDataSource" ref="dataSource" />
<beans:property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<beans:property name="packagesToScan" value="com.plm.conn.model" />
</beans:bean>
<!-- Transaction adapter -->
<beans:bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<beans:property name="databasePlatform"
value="org.hibernate.dialect.DerbyDialect" />
<beans:property name="showSql" value="true" />
<beans:property name="generateDdl" value="false" />
</beans:bean>
<!-- Transaction Manager -->
<beans:bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="emf" />
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<beans:bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- tx:annotation-driven /-->
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.plm.conn.model" />
Service
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional
#Component
#Service
public class QueueService implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory
.getLogger(QueueService.class);
#PersistenceContext
private EntityManager em;
#Transactional
public void addQueue(Queue queue) {
logger.info(" info..."+em.toString());
em.persist(queue);
}
#Transactional
public List<Queue> getAll() {
TypedQuery<Queue> query = em.createNamedQuery("Queue.findAll",
Queue.class);
logger.info(" info..." + query.getResultList());
return query.getResultList();
}
}
and my controller where i am calling the queue
package com.plm.conn.hcontroller;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.plm.conn.model.Queue;
import com.plm.conn.model.QueueService;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory
.getLogger(HomeController.class);
#Autowired
private QueueService queueSvc;
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
public String home(Locale locale, Model model, HttpServletRequest request,
HttpServletResponse response) {
Queue queue = new Queue();
//queue.setMsgidProd("1212121212");
//queueSvc.addQueue(queue);
logger.info(queueSvc.toString());
model.addAttribute("list", queueSvc.getAll());
return "home";
}
}
I can see some improvement needs to be done in the code.
1.Why you have annotated QueueService class with #Component,#Repository and #Service annotation all together,as per the code it contains,it should be annotated only with #Repository.
2.You have used #Transactional annotation at the class level,remove it from the individual method from this class.
3.In your servlet-context.xml file,you have below line
<context:component-scan base-package="com.plm.conn.model" />
make sure that you should have configured it correctly,it should scan the spring managed component,not your database entity,because according to your servlet-context.xml file,"com.plm.conn.model" is your entity package(see <beans:property name="packagesToScan" value="com.plm.conn.model" />)
I want to persist data without persistence.xml file. this is why I use Queue.java entity class which is in the com.plm.conn.model
I am new to the Spring I learned that we can persist the data without using persistence class. I modified servlet-context.xml as follows
<!-- Derby configuration -->
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName"
value="org.apache.derby.jdbc.ClientDriver" />
<beans:property name="url"
value="jdbc:derby://localhost:1527//plmbridge;create=false" />
<beans:property name="username" value="plmt" />
</beans:bean>
<!-- EntityManagerFactory -->
<beans:bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<beans:property name="packagesToScan" value="com.plm.conn.model" />
</beans:bean>
<!-- Transaction adapter -->
<beans:bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<beans:property name="databasePlatform"
value="org.hibernate.dialect.DerbyDialect" />
<beans:property name="showSql" value="true" />
<beans:property name="generateDdl" value="false" />
</beans:bean>
<!-- Transaction Manager -->
<beans:bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="emf" />
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<beans:bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- tx:annotation-driven /-->
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.plm.conn.model" />
and the Queue.java file here
package com.plm.conn.model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the QUEUE database table.
*
*/
#Entity
#Table(name="QUEUE")
#NamedQuery(name="Queue.findAll", query="SELECT q FROM Queue q")
public class Queue implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.TABLE)
#Column(name="QUEUE_ID", unique=true, nullable=false)
private int queueId;
#Column(length=250)
private String container;
private long expiration;
#Column(nullable=false, length=100)
private String id;
#Lob
private byte[] msg;
#Column(name="MSGID_PROD", length=250)
private String msgidProd;
#Column(name="MSGID_SEQ")
private long msgidSeq;
private long priority;
#Column(length=250)
private String xid;
//bi-directional one-to-one association to Completedjob
#OneToOne(mappedBy="queue")
private Completedjob completedjob;
//bi-directional one-to-one association to Failedjob
#OneToOne(mappedBy="queue")
private Failedjob failedjob;
public Queue() {
}
public int getQueueId() {
return this.queueId;
}
public void setQueueId(int queueId) {
this.queueId = queueId;
}
public String getContainer() {
return this.container;
}
public void setContainer(String container) {
this.container = container;
}
public long getExpiration() {
return this.expiration;
}
public void setExpiration(long expiration) {
this.expiration = expiration;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public byte[] getMsg() {
return this.msg;
}
public void setMsg(byte[] msg) {
this.msg = msg;
}
public String getMsgidProd() {
return this.msgidProd;
}
public void setMsgidProd(String msgidProd) {
this.msgidProd = msgidProd;
}
public long getMsgidSeq() {
return this.msgidSeq;
}
public void setMsgidSeq(long msgidSeq) {
this.msgidSeq = msgidSeq;
}
public long getPriority() {
return this.priority;
}
public void setPriority(long priority) {
this.priority = priority;
}
public String getXid() {
return this.xid;
}
public void setXid(String xid) {
this.xid = xid;
}
public Completedjob getCompletedjob() {
return this.completedjob;
}
public void setCompletedjob(Completedjob completedjob) {
this.completedjob = completedjob;
}
public Failedjob getFailedjob() {
return this.failedjob;
}
public void setFailedjob(Failedjob failedjob) {
this.failedjob = failedjob;
}
}
I am able to query the tables but I cant store the data I get the error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: error performing isolated work
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:965)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
ERROR 42X05: Table/View 'HIBERNATE_SEQUENCES' does not exist.
org.apache.derby.client.am.ClientStatement.completeSqlca(Unknown Source)
org.apache.derby.client.net.NetStatementReply.parsePrepareError(Unknown Source)
org.apache.derby.client.net.NetStatementReply.parsePRPSQLSTTreply(Unknown Source)
org.apache.derby.client.net.NetStatementReply.readPrepareDescribeOutput(Unknown Source)
org.apache.derby.client.net.StatementReply.readPrepareDescribeOutput(Unknown Source)
org.apache.derby.client.net.NetStatement.readPrepareDescribeOutput_(Unknown Source)
org.apache.derby.client.am.ClientStatement.readPrepareDescribeOutput(Unknown Source)
org.apache.derby.client.am.ClientPreparedStatement.readPrepareDescribeInputOutput(Unknown Source)
org.apache.derby.client.am.ClientPreparedStatement.flowPrepareDescribeInputOutput(Unknown Source)
org.apache.derby.client.am.ClientPreparedStatement.prepare(Unknown Source)
org.apache.derby.client.am.ClientConnection.prepareStatementX(Unknown Source)
org.apache.derby.client.am.ClientConnection.prepareStatement(Unknown Source)
org.hibernate.id.MultipleHiLoPerTableGenerator.prepareStatement(MultipleHiLoPerTableGenerator.java:243)
org.hibernate.id.MultipleHiLoPerTableGenerator.access$200(MultipleHiLoPerTableGenerator.java:86)
org.hibernate.id.MultipleHiLoPerTableGenerator$1.execute(MultipleHiLoPerTableGenerator.java:159)
org.hibernate.id.MultipleHiLoPerTableGenerator$1.execute(MultipleHiLoPerTableGenerator.java:152)
org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:72)
org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:51)
org.hibernate.engine.transaction.internal.jdbc.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:74)
org.hibernate.id.MultipleHiLoPerTableGenerator$2.getNextValue(MultipleHiLoPerTableGenerator.java:221)
org.hibernate.id.enhanced.LegacyHiLoAlgorithmOptimizer.generate(LegacyHiLoAlgorithmOptimizer.java:77)
org.hibernate.id.MultipleHiLoPerTableGenerator.generate(MultipleHiLoPerTableGenerator.java:218)
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:291)
com.sun.proxy.$Proxy33.persist(Unknown Source)
com.plm.conn.model.QueueService.addQueue(QueueService.java:37)
com.plm.conn.model.QueueService$$FastClassBySpringCGLIB$$6b3c7d41.invoke(<generated>)
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
com.plm.conn.model.QueueService$$EnhancerBySpringCGLIB$$77572cff.addQueue(<generated>)
com.plm.conn.hcontroller.HomeController.home(HomeController.java:63)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:685)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Related
I'm creating a Spring MVC application. And I have a Basket bean that has few autowired beans in in.
#Component
public class Basket {
#Autowired
#Qualifier("CPContainer")
private CPContainer cpContainer;
#Autowired
#Qualifier("FBContainer")
private FBContainer fbContainer;
public CPContainer getCpContainer() {
return cpContainer;
}
public void setCpContainer(CPContainer cpContainer) {
this.cpContainer = cpContainer;
}
public FBContainer getFbContainer() {
return fbContainer;
}
public void setFbContainer(FBContainer fbContainer) {
this.fbContainer = fbContainer;
}
Autowired beans CPContainer and FBContainer have List inside of them wired with list in dispather-servltet.xml via #Resource annotation:
#Component
public class FBContainer implements Container {
#Resource(name = "FBList")
private List<FBProduct> products;
private int id;
private int amount;
#Override
public List<FBProduct> getProducts() {
return products;
}
#Override
public FBProduct getProductById(int id) {
return products.get(id);
}
dispatcher-servltet.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans ...
<mvc:annotation-driven/>
<context:component-scan base-package="com.concrete"/>
<util:list id="FBList" value-type="com.concrete.pojo.product.FBProduct">
<bean id="fb1" class="com.concrete.pojo.product.FBProduct">
<property name="id" value="0"/>
<property name="mass" value="1000"/>
<property name="l" value="8980"/>
<property name="b" value="1490"/>
<property name="h" value="220"/>
</bean>
<bean id="fb2" class="com.concrete.pojo.product.FBProduct">
<property name="id" value="1"/>
<property name="mass" value="2000"/>
<property name="l" value="8980"/>
<property name="b" value="1190"/>
<property name="h" value="220"/>
</bean>
<bean id="fb3" class="com.concrete.pojo.product.FBProduct">
<property name="id" value="2"/>
<property name="mass" value="3000"/>
<property name="l" value="7180"/>
<property name="b" value="1490"/>
<property name="h" value="220"/>
</bean>
</util:list>
<bean id="FBContainer" class="com.concrete.pojo.container.FBContainer">
<property name="products" ref="FBList"/>
</bean>
<bean id="CPContainer" class="com.concrete.pojo.container.CPContainer">
<property name="products" ref="CPList"/>
</bean>
</beans>
I'm adding Basket class to a model as model attribute, wich I intend to use in jsp page to get data from Container's List(Like FBProducts in FBContainer). But when i try to access a List I get null pointer exception :
java.lang.NullPointerException
com.concrete.pojo.container.FBContainer.getProductById(FBContainer.java:25)
com.concrete.pojo.container.Basket.calculateMass(Basket.java:24)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
javax.el.BeanELResolver.invoke(BeanELResolver.java:183)
org.apache.jasper.el.JasperELResolver.invoke(JasperELResolver.java:139)
org.apache.el.parser.AstValue.getValue(AstValue.java:174)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:950)
org.apache.jsp.calculate_jsp._jspService(calculate_jsp.java:93)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:314)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1069)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1008)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
MainController.class :
#Controller
public class MainController {
#Autowired
#Qualifier("basket")
private Basket basket;
#RequestMapping(value = "/calculate",method = RequestMethod.POST)
public String calculate(Model model,Basket basket){
model.addAttribute("Basket",basket);
return "calculate";
}
}
I think i found the solution. It appears I was adding wrong object to model of calculate method inside MainController :
#RequestMapping(value = "/calculate",method = RequestMethod.GET)
public String calculate(Model model,Basket basket){
model.addAttribute("Basket",basket);
return "calculate";
}
So, I removed Basket argument from method and NullPointerException is solved :
#RequestMapping(value = "/calculate",method = RequestMethod.GET)
public String calculate(Model model){
model.addAttribute("Basket",basket);
return "calculate";
}
I am getting the exception below, and I am not sure what is the reason.
my controller
package com.attar.test.controller;
import static
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.attar.test.entity.Patient;
import com.attar.test.service.Patientservice;
#org.springframework.stereotype.Controller
#RequestMapping("/user")
public class Controller {
#Autowired
private Patientservice patientservice;
#InitBinder
public void initbinderprocess(WebDataBinder databinder) {
StringTrimmerEditor trimedit = new StringTrimmerEditor(true);
databinder.registerCustomEditor(String.class, trimedit);
}
#RequestMapping("/frame")
public String datauser(Model model) {
Patient theuse = new Patient();
model.addAttribute("userr", theuse);
return "user-data";
}
#RequestMapping(value = "/userdata", method = RequestMethod.POST)
public String datashow(#Valid #ModelAttribute("userr") Patient thesuer, BindingResult bindresult) {
if (!bindresult.hasErrors()) {
patientservice.savepatient(thesuer);
return "show-data";
} else {
// return "redirect:/user/frame";
return "user-data";
}
}
}
PatientDaoimpl
package com.attar.test.dao;
import javax.validation.Valid;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.attar.test.entity.Patient;
#Repository
public class PatientDaoimpl implements PatientDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public void savepatient(#Valid Patient thesuer) {
Session session = sessionFactory.openSession();
session.save(thesuer);
}
}
PatientServiceimpl
package com.attar.test.service;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.attar.test.dao.PatientDao;
import com.attar.test.entity.Patient;
#Service
public class PatientServiceimpl implements Patientservice {
#Autowired
private PatientDao patientdao;
#Override
#Transactional
public void savepatient(#Valid Patient thesuer) {
patientdao.savepatient(thesuer);
}
}
my patient-entity
package com.attar.test.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#Entity
#Table(name = "patient")
public class Patient {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#NotNull(message = "it is required")
#Column(name = "first_name")
private String first_name;
#Column(name = "last_name")
private String last_name;
#Column(name = "age")
private Integer age;
public Patient() {
}
public Patient(#NotNull(message = "it is required") String first_name, String last_name, int age) {
this.first_name = first_name;
this.last_name = last_name;
this.age = age;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
WebContent/WEB-INF/spring-mvc-demo-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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
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
">
<!-- <aop:aspectj-autoproxy /> -->
<!-- Add support for component scanning -->
<context:component-scan base-package="com.attar.test" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven />
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/patients?useSSL=false" />
<property name="user" value="dbuser" />
<property name="password" value="dbpassword" />
<!-- these are connection pool properties for C3P0 -->
<property name="initialPoolSize" value="5" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.luv2code.springdemo.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
<mvc:resources location="/resources/" mapping="/resources/**" />
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="resources/messages" />
</bean>
</beans>
my error-exception
HTTP Status 500 – Internal Server Error
--------------------------------------------------------------------------------
Type Exception Report
Message Request processing failed; nested exception is org.hibernate.MappingException: Unknown entity: com.attar.test.entity.Patient
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.MappingException: Unknown entity: com.attar.test.entity.Patient
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
org.hibernate.MappingException: Unknown entity: com.attar.test.entity.Patient
org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)
org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1634)
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:689)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:681)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:676)
com.attar.test.dao.PatientDaoimpl.savepatient(PatientDaoimpl.java:20)
com.attar.test.service.PatientServiceimpl.savepatient(PatientServiceimpl.java:20)
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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
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:213)
com.sun.proxy.$Proxy89.savepatient(Unknown Source)
com.attar.test.controller.Controller.datashow(Controller.java:45)
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.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.
--------------------------------------------------------------------------------
Apache Tomcat/8.5.20
I tried to put all lib for spring and hibernate. I don't know what is the cause of the problem.
You have to adopt the property "packageToScan" in your spring-mvc-demo-servlet.xml. It should specify your entity package (com.attar.test.entity).
I try to develop some server program using spring mvc and hibernate.
At my tables, some tables have two primray keys.
So, I want to use these keys.
Simply, I use double #Id annotations.
In the result, I got org.hibernate.TypeMismatchException.
Although I searched to solve error, I can't solve this problem...
help me please.
This is my model class.
package kr.ac.jbnu.jinggumdari.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.NaturalId;
import org.hibernate.annotations.Parameter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name="festival_info")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Interest implements Serializable{
#Id
#Column(name="interest")
private String interest;
#Id
#Column(name="festival_number", unique=true, nullable=false)
#GeneratedValue(generator="gen")
#GenericGenerator(name="gen", strategy="foreign", parameters=#Parameter(name="property", value="festival_info"))
private String festivalNumber;
public Interest(){
festivalNumber = "";
interest = "";
}
public Interest(String festivalNumber, String interest) {
this.festivalNumber = festivalNumber;
this.interest = interest;
}
public String getFestivalNumber() {
return festivalNumber;
}
public void setFestival_number(String festivalNumber) {
this.festivalNumber = festivalNumber;
}
public String getInterest() {
return interest;
}
public void setInterest(String interest) {
this.interest = interest;
}
#Override
public String toString(){
return festivalNumber + "," + interest;
}
}
This is my servlet-context.xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<beans:property name="favorPathExtension" value="true" />
<beans:property name="ignoreAcceptHeader" value="true" />
<beans:property name="mediaTypes">
<beans:map>
<beans:entry key="json" value="application/json" />
<beans:entry key="html" value="text/html" />
</beans:map>
</beans:property>
</beans:bean>
<context:component-scan base-package="kr.ac.jbnu.jinggumdari" />
<beans:bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/jinggumdari" />
<beans:property name="username" value="root" />
<beans:property name="password" value="mysql1234" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>kr.ac.jbnu.jinggumdari.model.Member</beans:value>
<beans:value>kr.ac.jbnu.jinggumdari.model.Festival</beans:value>
<beans:value>kr.ac.jbnu.jinggumdari.model.FestivalImage</beans:value>
<beans:value>kr.ac.jbnu.jinggumdari.model.Interest</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
<beans:property name="packagesToScan" value="com.hibernate.yourpackage" />
</beans:bean>
<beans:bean id="memberDAO" class="kr.ac.jbnu.jinggumdari.DAO.MemberDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="memberService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.MemberServiceImpl">
<beans:property name="memberDAO" ref="memberDAO"></beans:property>
</beans:bean>
<beans:bean id="festivalDAO" class="kr.ac.jbnu.jinggumdari.DAO.FestivalDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="festivalService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.FestivalServiceImpl">
<beans:property name="festivalDAO" ref="festivalDAO"></beans:property>
</beans:bean>
<beans:bean id="festivalImageDAO" class="kr.ac.jbnu.jinggumdari.DAO.FestivalImageDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="festivalImageService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.FestivalImageServiceImpl">
<beans:property name="festivalImageDAO" ref="festivalImageDAO"></beans:property>
</beans:bean>
<beans:bean id="interestDAO" class="kr.ac.jbnu.jinggumdari.DAO.InterestDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="interestService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.InterestServiceImpl">
<beans:property name="interestDAO" ref="interestDAO"></beans:property>
</beans:bean>
<beans:bean id="reviewDAO" class="kr.ac.jbnu.jinggumdari.DAO.ReviewDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="reviewService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.ReviewServiceImpl">
<beans:property name="reviewDAO" ref="reviewDAO"></beans:property>
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
</beans:beans>
This is my DAO.
package kr.ac.jbnu.jinggumdari.DAO;
import java.util.List;
import kr.ac.jbnu.jinggumdari.model.Interest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
public class InterestDAOImpl implements InterestDAO {
private static final Logger logger = LoggerFactory
.getLogger(FestivalDAOImpl.class);
private SessionFactory sessionFactory;
private boolean isSuccess;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
#Override
#Transactional
public boolean addInterest(Interest interest) {
// TODO Auto-generated method stub
isSuccess = false;
Session session = this.sessionFactory.getCurrentSession();
session.persist(interest);
logger.info("Festival saved successfully, Festival Details=" + interest);
isSuccess = true;
return isSuccess;
}
#Override
#Transactional
public boolean modifyInterest(Interest interest) {
// TODO Auto-generated method stub
isSuccess = false;
Session session = this.sessionFactory.getCurrentSession();
session.update(interest);
logger.info("Festival modified successfully, Festival Details="
+ interest);
isSuccess = true;
return isSuccess;
}
#Override
#Transactional
public boolean removeInterests(String festivalNumber) {
// TODO Auto-generated method stub
isSuccess = false;
Session session = this.sessionFactory.getCurrentSession();
Long numberOfInterests = getNumberOfInterests(festivalNumber, session);
for (int i = 0; i < numberOfInterests; i++) {
Interest targetInterest = (Interest) session.load(Interest.class,
festivalNumber);
if (targetInterest != null) {
session.delete(targetInterest);
}
logger.info("Interest deleted successfully, Interest details="
+ targetInterest);
}
isSuccess = true;
return isSuccess;
}
#Override
#Transactional
public List<Interest> getInterests(String festivalNumber) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
List<Interest> interestsList = session.createQuery("from Interest")
.list();
for (Interest i : interestsList) {
logger.info("Person List::" + i);
}
return interestsList;
}
#Transactional
private Long getNumberOfInterests(String festivalNUmber, Session session) {
String hql = "Select count(*) from Interest where festival_number='"
+ festivalNUmber + "'";
List list = session.createQuery(hql).list();
return (Long) list.get(0);
}
}
This is error stack.
org.hibernate.TypeMismatchException: Provided id of the wrong type for class kr.ac.jbnu.jinggumdari.model.Interest. Expected: class kr.ac.jbnu.jinggumdari.model.Interest, got class java.lang.String
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:134)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1106)
at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.getReference(SessionImpl.java:2564)
at org.hibernate.internal.SessionImpl.load(SessionImpl.java:981)
at kr.ac.jbnu.jinggumdari.DAO.InterestDAOImpl.removeInterests(InterestDAOImpl.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy54.removeInterests(Unknown Source)
at kr.ac.jbnu.jinggumdari.serviceImplementation.InterestServiceImpl.removeInterests(InterestServiceImpl.java:31)
at kr.ac.jbnu.jinggumdari.controller.JinggumdariController.test2(JinggumdariController.java:309)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Your problem is that you are using two #Id annotations in the same entity, you would rather use #EmbeddeId instead, so change this code:
#Id
#Column(name="interest")
private String interest;
#Id
#Column(name="festival_number", unique=true, nullable=false)
#GeneratedValue(generator="gen")
#GenericGenerator(name="gen", strategy="foreign", parameters=#Parameter(name="property", value="festival_info"))
private String festivalNumber;
To the following code:
public class Interest implements Serializable{
#EmbeddedId
private InterestId id;
//getters and setters and the rest of your code go here
}
And the InterestId class:
#Embeddable
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name="interest")
private String interest;
#Column(name="festival_number", unique=true, nullable=false)
#GeneratedValue(generator="gen")
#GenericGenerator(name="gen", strategy="foreign", parameters=#Parameter(name="property", value="festival_info"))
private String festivalNumber;
// and getters and setters here
}
You can refer to this tutorial and the Documentation here for further information.
You cannot use 2 #Id annotations for a composite primary key. You have to use #EmbeddedId Check this documentation and this Stackoverflow link.
I want to add object data and want to save in DB table, everything working fine but it gives me an error :
java.lang.NullPointerException
on line getSession().save(entity);
I have called this method in code :
#Service
public class AddCategoryProcessor implements ICommandProcessor<AddCategory> {
#Autowired
private IPatronCategoryRepository patronCategoryRepository = new PatronCategoryRepository();
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void Process(AddCategory command){
PatronCategory entity = new PatronCategory();
entity.setCategoryName(command.getCategoryName());
try
{
patronCategoryRepository.save(entity);
}catch (Exception e){
e.printStackTrace();
}
}
}
following is my xml file :
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/abc"/>
<property name="username" value="postgres"/>
<property name="password" value="pwd"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.ngl.domain"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
Here is a getSession() method :
#Override
public Session getSession() {
return getSessionFactory().getCurrentSession();
}
Here is a sessionFactory declaration :
protected SessionFactory sessionFactory;
Any guesses why it's NULLPOINTEREXCEPTION ??
UPDATE :
java.lang.NullPointerException
at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:32)
at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:16)
at com.ngl.controllerapis.BaseApiController.ProcessRequest(BaseApiController.java:29)
at com.ngl.controllerapis.PatronCategoryController.addCategory(PatronCategoryController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
and xml for transaction manager
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
in repository
#Autowired
protected SessionFactory sessionFactory;
Your config is a bit incomplete. You should delegate session management completely to Spring
Add in you spring xml file:
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Then, in your PatronCategoryRepository class, extend HibernateDaoSupport and add this constructor:
public class PatronCategoryRepository extends HibernateDaoSupport implements IPatronCategoryRepository{
#Autowired
public PatronCategoryRepository(HibernateTemplate hibernateTemplate) {
super();
super.setHibernateTemplate(hibernateTemplate);
}
[...]
}
In AddCategoryProcessor, leave the definition of the repository like this:
#Autowired
private IPatronCategoryRepository patronCategoryRepository;
And finally your method:
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void Process(AddCategory command){
PatronCategory entity = new PatronCategory();
entity.setCategoryName(command.getCategoryName());
try
{
getHibernateTemplate.save(entity);
}catch (Exception e){
e.printStackTrace();
}
}
In case you still need to access directy the SessionFactory, the only thing you have to do is inject it into PatronCategoryRepository:
#Repository
public class PatronCategoryRepository implements IPatronCategoryRepository{
#Autowired
protected SessionFactory sessionFactory;
public PatronCategoryRepository() {
}
public PatronCategory save(PatronCategory entity){
return getSession().save(entity);
}
private Session getSession() {
return sessionFactory.getCurrentSession();
}
}
And remember to remove the new clause from AddCategoryProcessor, leaving it like this:
#Autowired
private IPatronCategoryRepository patronCategoryRepository;
Employee.java
package com.javacodegeeks.snippets.enterprise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "Employee1")
public class Employee implements Serializable {
#Id
#Column(name = "ID")
private int id;
#Column(name = "NAME")
private String name;
#Column(name = "AGE")
private int age;
public Employee() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
EmployeeDao.java
package com.javacodegeeks.snippets.enterprise.dao;
import com.javacodegeeks.snippets.enterprise.model.Employee;
public interface EmployeeDAO {
public void saveEmployee(Employee employee);
Employee findEmployeeById(int id);
void updateEmployee(Employee employee);
void deleteEmployee(Employee employee);
}
EmployeeDaoImpl.java
package com.javacodegeeks.snippets.enterprise.dao;
import java.io.Serializable;
import org.hibernate.SessionException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.javacodegeeks.snippets.enterprise.model.Employee;
public class EmployeeDAOImpl implements EmployeeDAO {
private HibernateTemplate template;
private SessionFactory sessionFactory;
#Autowired
public void setTemplate(HibernateTemplate template) {
this.template = template;
// template.setSessionFactory(sessionFactory);
}
public void setSessionFactory(SessionFactory sessionFactory) {
new HibernateTemplate(sessionFactory);
}
/*
* public void saveEmployee(Employee employee) {
* sessionFactory.getCurrentSession().save(employee);
*
* }
*/
public Employee findEmployeeById(int id) {
return (Employee) sessionFactory.getCurrentSession().get(
Employee.class, id);
}
public void updateEmployee(Employee employee) {
sessionFactory.getCurrentSession().update(employee);
}
public void deleteEmployee(Employee employee) {
sessionFactory.getCurrentSession().delete(employee);
}
public void saveEmployee(Employee employee) {
sessionFactory.getCurrentSession().persist(employee);
template.saveOrUpdate(employee);
}
}
Application COntext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package="com.javacodegeeks.snippets.enterprise.*" />
<!-- <tx:annotation-driven/> -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.javacodegeeks.snippets.enterprise.model.Employee</value>
</list>
</property>
<!-- <property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property> -->
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> -->
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="d" class="com.javacodegeeks.snippets.enterprise.dao.EmployeeDAOImpl">
<property name="template" ref="template"></property>
</bean>
</beans>
pleas ehelp me :-)
I dont know what is wrong in my listContacts in controller
map.put("contactList", contactService.listContact());
Can somebody help me?
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/test] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at pl.ivmx.contact.controller.ContactController.listContacts(ContactController.java:26)
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:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
package pl.ivmx.contact.controller;
import java.util.Map;
import pl.ivmx.contact.dao.ContactDAO;
import pl.ivmx.contact.form.Contact;
import pl.ivmx.contact.service.ContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class ContactController {
#Autowired
private ContactService contactService;
#RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
map.put("contact", new Contact());
map.put("contactList", contactService.listContact());
return "/contact";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact") Contact contact,
BindingResult result) {
contactService.addContact(contact);
return "redirect:/contact";
}
#RequestMapping("/delete/{contactId}")
public String deleteContact(#PathVariable("contactId") Integer contactId) {
contactService.removeContact(contactId);
return "redirect:/contact";
}
}
package pl.ivmx.contact.dao;
import java.util.List;
import pl.ivmx.contact.form.Contact;
public interface ContactDAO {
public void addContact(Contact contact);
public List<Contact> listContact();
public void removeContact(Integer id);
}
package pl.ivmx.contact.dao;
import java.util.List;
import pl.ivmx.contact.form.Contact;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class ContactDAOImpl implements ContactDAO {
#Autowired
private SessionFactory sessionFactory;
public void addContact(Contact contact) {
sessionFactory.getCurrentSession().save(contact);
}
public List<Contact> listContact() {
return sessionFactory.getCurrentSession().createQuery("from Contact").list();
}
public void removeContact(Integer id) {
Contact contact = (Contact) sessionFactory.getCurrentSession().load(
Contact.class, id);
if (null != contact) {
sessionFactory.getCurrentSession().delete(contact);
}
}
}
package pl.ivmx.contact.service;
import java.util.List;
import pl.ivmx.contact.form.Contact;
public interface ContactService {
public void addContact(Contact contact);
public List<Contact> listContact();
public void removeContact(Integer id);
}
package pl.ivmx.contact.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.ivmx.contact.dao.ContactDAO;
import pl.ivmx.contact.form.Contact;
#Service
public class ContactServiceImpl implements ContactService {
#Autowired
private ContactDAO contactDAO;
#Transactional
public void addContact(Contact contact) {
contactDAO.addContact(contact);
}
#Transactional
public List<Contact> listContact() {
return contactDAO.listContact();
}
#Transactional
public void removeContact(Integer id) {
contactDAO.removeContact(id);
}
}
package pl.ivmx.contact.form;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="CONTACTS")
public class Contact {
#Id
#Column(name="ID")
#GeneratedValue
private Integer id;
#Column(name="FIRSTNAME")
private String firstname;
#Column(name="LASTNAME")
private String lastname;
#Column(name="EMAIL")
private String email;
#Column(name="TELEPHONE")
private String telephone;
public String getEmail() {
return email;
}
public String getTelephone() {
return telephone;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/pages/index.jsp</welcome-file>
</welcome-file-list>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="pl.ivmx.contact" />
<!-- <bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="messages_en.properties" />
<property name="defaultEncoding" value="UTF-8" />
</bean> -->
<import resource="commonContext.xml" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="userTestDao" class="pl.ivmx.dao.impl.UserTestDaoImpl">
<!-- <property name="dataSource" ref="dataSource" /> -->
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
<!-- class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> -->
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="META-INF/hibernate.cfg.xml" />
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<!-- <property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>pl.ivmx.model.UserTest</value>
</list>
</property> -->
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
dispatcher-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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> -->
<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>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/index.do"> <ref bean="index" /></entry>
<entry key="/registration.do"> <ref bean="registration" /></entry>
<entry key="/usertestlist.do"> <ref bean="usertest" /></entry>
<entry key="/contact.do"> <ref bean="contact" /></entry>
</map>
</property>
</bean>
<bean id="index" class="pl.ivmx.web.IndexController"/>
<bean id="registrationValidator" class="pl.ivmx.validation.RegistrationValidator" />
<bean id="registration" class="pl.ivmx.web.RegistrationFormController" >
<property name="commandName"><value>userTest</value></property>
<property name="commandClass"><value>pl.ivmx.model.UserTest</value></property>
<property name="validator"><ref local="registrationValidator"/></property>
<property name="formView"><value>registration</value></property>
<property name="successView"><value>registrationsuccess</value></property>
<property name="userTestDao"><ref bean="userTestDao"/></property>
</bean>
<bean id="usertest" class="pl.ivmx.web.UserTestController">
<property name="userTestDao"><ref bean="userTestDao"/></property>
</bean>
<bean id="contact" class="pl.ivmx.contact.controller.ContactController">
</bean>
<bean id="contactService" class="pl.ivmx.contact.service.ContactServiceImpl">
</bean>
<bean id="contactDAO" class="pl.ivmx.contact.dao.ContactDAOImpl">
</bean>
</beans>
It looks like a NullPointerException thrown in the method here:
#RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
map.put("contact", new Contact());
map.put("contactList", contactService.listContact());
return "/contact";
}
I would debug and check that contactService has been autowired correctly.
The null pointer is line 26, if that is the line containing contactService.listContact() then contactService is null. If it is the line above then the map is null.
I am not sure but try adding:
<context:component-scan base-package="pl.ivmx.contact" />
to the dispatcher-servlet.xml as well, it could be that the annotation isnt getting processed
you are returning "/contact" there in the method as a view to be shown:
#RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
map.put("contact", new Contact());
map.put("contactList", contactService.listContact());
return "/contact"; // <---- here!
}
This means that you should have a view named /contact defined somewhere, but I don't see it. You need to have a view that corresponds with the value you're defining.
You probably want to return a value like "contact" instead of "/contact" and then have contact.jsp in the webapp/WEB-INF/views folder (assuming you use maven standard directory layout).
I don't see anything obvious ... could sessionFactory be null? Should be easy to find, tho. Step through the code in the debugger.
I think you are missing to add the contactService bean to your applicationContext.xml
try adding the below to tags
<bean id="contactService" class="pl.ivmx.contact.service.ContactServiceImpl">
<property name="contactDAO" ref="contactDAO" />
</bean>
<bean id="contactDAO" class="pl.ivmx.contact.dao.ContactDAOImpl" />