I have the following JPA entity (generated with Netbeans):
package com.tsystems.tf.db.models;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author johorvat
*/
#Entity
#Table(name = "TABLE1")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Testcase.findAll", query = "SELECT t FROM Testcase t")
})
public class Testcase implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#Column(name = "TESTCASE_ID")
private BigDecimal testcaseId;
#Basic(optional = false)
#Column(name = "TESTCASE_NAME")
private String testcaseName;
#Basic(optional = false)
#Column(name = "CREATOR")
private String creator;
#Basic(optional = false)
#Column(name = "CREATED_AT")
#Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
#Column(name = "LAST_RUN")
#Temporal(TemporalType.TIMESTAMP)
private Date lastRun;
#Column(name = "LAST_RUN_RESULT")
private Character lastRunResult;
#Column(name = "INPUT")
private String input;
#Column(name = "OUTPUT")
private String output;
public Testcase() {
}
public Testcase(BigDecimal testcaseId) {
this.testcaseId = testcaseId;
}
public Testcase(BigDecimal testcaseId, String testcaseName, String creator, Date createdAt) {
this.testcaseId = testcaseId;
this.testcaseName = testcaseName;
this.creator = creator;
this.createdAt = createdAt;
}
public BigDecimal getTestcaseId() {
return testcaseId;
}
public void setTestcaseId(BigDecimal testcaseId) {
this.testcaseId = testcaseId;
}
public String getTestcaseName() {
return testcaseName;
}
public void setTestcaseName(String testcaseName) {
this.testcaseName = testcaseName;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getLastRun() {
return lastRun;
}
public void setLastRun(Date lastRun) {
this.lastRun = lastRun;
}
public Character getLastRunResult() {
return lastRunResult;
}
public void setLastRunResult(Character lastRunResult) {
this.lastRunResult = lastRunResult;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getOutput() {
return output;
}
public void setOutput(String output) {
this.output = output;
}
#Override
public int hashCode() {
int hash = 0;
hash += (testcaseId != null ? testcaseId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Testcase)) {
return false;
}
Testcase other = (Testcase) object;
if ((this.testcaseId == null && other.testcaseId != null) || (this.testcaseId != null && !this.testcaseId.equals(other.testcaseId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.tsystems.tf.db.models.Testcase[ testcaseId=" + testcaseId + " ]";
}
}
I try to implement CRUD operations for this entity using Hibernate but I get LazyEvaluationException. There are NO references. Its only 1 table in the database... I can query but when I try to issue update the exception is being thrown. Now I have a really naive implementation that looks like the following:
package com.tsystems.tf.dao.impl;
import com.tsystems.tf.dao.ITestcaseDAO;
import com.tsystems.tf.db.models.Testcase;
import java.math.BigDecimal;
import java.util.Collection;
import javax.transaction.Transactional;
import org.apache.catalina.tribes.util.Arrays;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.jboss.logging.Logger;
public class TestcaseDAOImpl implements ITestcaseDAO {
private static final SessionFactory sessionFactory;
static {
Configuration configuration = new Configuration();
configuration = configuration.configure();
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
registryBuilder = registryBuilder.applySettings(configuration.getProperties());
StandardServiceRegistry registry = registryBuilder.build();
sessionFactory = configuration.buildSessionFactory(registry);
}
#Override
public Collection<Testcase> getAllTestcase() {
Session session = sessionFactory.openSession();
Transaction transaction = null;
Collection<Testcase> testcaseCollection = null;
try {
transaction = session.beginTransaction();
Query query = session.getNamedQuery("Testcase.findAll");
testcaseCollection = query.list();
transaction.commit();
} catch (final HibernateException ex) {
Logger.getLogger(TestcaseDAOImpl.class)
.error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));
if (transaction != null)
transaction.rollback();
}
session.close();
return testcaseCollection;
}
#Override
public void createTestcase(Testcase testcase) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public Testcase readTestcase(BigDecimal id) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
Testcase testcase = null;
try {
transaction = session.beginTransaction();
testcase = (Testcase) session.load(Testcase.class, id);
transaction.commit();
} catch (final HibernateException ex) {
Logger.getLogger(TestcaseDAOImpl.class)
.error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));
if (transaction != null)
transaction.rollback();
}
session.close();
return testcase;
}
#Override
public void updateTestcase(Testcase testcase) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.update(testcase);
transaction.commit();
} catch (final HibernateException ex) {
Logger.getLogger(TestcaseDAOImpl.class)
.error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));
if (transaction != null)
transaction.rollback();
}
session.close();
}
#Override
public void deleteTestcase(BigDecimal testcaseId) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
When the update is being called bamm No Session. Why is this happening? GetAll succeeds nice and smooth but that's all to it. Everything else returns in No Session error in my logs.
StackTrace:
14-Nov-2014 16:54:43.012 WARNING [http-apr-8080-exec-148] com.sun.faces.context.SessionMap.put JSF1063: WARNING! Setting non-serializable attribute value into HttpSession (key: testcaseProvider, value class: com.tsystems.tf.beans.TestcaseProvider).
14-Nov-2014 16:54:46.812 WARNING [http-apr-8080-exec-148] com.sun.faces.lifecycle.InvokeApplicationPhase.execute #{testcaseProvider.updateTestcase()}: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
javax.faces.FacesException: #{testcaseProvider.updateTestcase()}: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 29 more
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.tsystems.tf.db.models.Testcase_$$_jvsta1c_0.setTestcaseName(Testcase_$$_jvsta1c_0.java)
at com.tsystems.tf.beans.TestcaseProvider.updateTestcase(TestcaseProvider.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 30 more
14-Nov-2014 16:54:46.832 SEVERE [http-apr-8080-exec-148] com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError javax.faces.el.EvaluationException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.tsystems.tf.db.models.Testcase_$$_jvsta1c_0.setTestcaseName(Testcase_$$_jvsta1c_0.java)
at com.tsystems.tf.beans.TestcaseProvider.updateTestcase(TestcaseProvider.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 30 more
replace your static block by a before() method, and add the session creation at the end of it :
#Before
public void before() {
Configuration configuration = new Configuration();
configuration = configuration.configure();
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
registryBuilder = registryBuilder.applySettings(configuration.getProperties());
StandardServiceRegistry registry = registryBuilder.build();
sessionFactory = configuration.buildSessionFactory(registry);
session = sessionFactory.openSession();
}
and an after() method :
#After
public void after {
session.close();
sessionFactory.close();
}
And of course, remove all open/close session in each test.
Related
i am trying to insert some record into my database table using spring hibernate,but the following error occur after running the project.please help me to solve the problem..thanks
Entity class Admin.java
package com.finalproject.entity;
// Generated Apr 20, 2017 4:49:19 PM by Hibernate Tools 4.3.1
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Admin generated by hbm2java
*/
#Entity
#Table(name="admin"
,catalog="advertisement_system"
)
public class Admin implements java.io.Serializable {
private Integer adminId;
private String adminName;
private String adminEmail;
private String adminPass;
private byte[] adminPhoto;
public Admin() {
}
public Admin(String adminName, String adminEmail, String adminPass) {
this.adminName = adminName;
this.adminEmail = adminEmail;
this.adminPass = adminPass;
}
public Admin(String adminName, String adminEmail, String adminPass, byte[] adminPhoto) {
this.adminName = adminName;
this.adminEmail = adminEmail;
this.adminPass = adminPass;
this.adminPhoto = adminPhoto;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="admin_id", unique=true, nullable=false)
public Integer getAdminId() {
return this.adminId;
}
public void setAdminId(Integer adminId) {
this.adminId = adminId;
}
#Column(name="admin_name", nullable=false, length=45)
public String getAdminName() {
return this.adminName;
}
public void setAdminName(String adminName) {
this.adminName = adminName;
}
#Column(name="admin_email", nullable=false, length=45)
public String getAdminEmail() {
return this.adminEmail;
}
public void setAdminEmail(String adminEmail) {
this.adminEmail = adminEmail;
}
#Column(name="admin_pass", nullable=false, length=45)
public String getAdminPass() {
return this.adminPass;
}
public void setAdminPass(String adminPass) {
this.adminPass = adminPass;
}
#Column(name="admin_photo")
public byte[] getAdminPhoto() {
return this.adminPhoto;
}
public void setAdminPhoto(byte[] adminPhoto) {
this.adminPhoto = adminPhoto;
}
}
AdminServiceImpl.java class
package com.finalproject.service.impl;
import com.finalproject.dao.AdminDao;
import com.finalproject.entity.Admin;
import com.finalproject.service.AdminService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
#Service("adminService")
#Transactional(propagation = Propagation.SUPPORTS,rollbackFor = Exception.class)
public class AdminServiceImpl implements AdminService {
#Autowired
AdminDao adminDao;
#Override
public void create(Admin admin) {
adminDao.create(admin);
}
#Override
public void update(Admin admin) {
adminDao.update(admin);
}
#Override
public void delete(Long adminId) {
adminDao.delete(adminId);
}
#Override
public Admin edit(Long adminId) {
return adminDao.edit(adminId);
}
#Override
public List<Admin> getAll() {
return adminDao.getAll();
}
#Override
public Admin find(Long adminId) {
return adminDao.find(adminId);
}
}
Dao implemented class AdminDaoImpl.java
package com.finalproject.dao.impl;
import com.finalproject.dao.AdminDao;
import com.finalproject.entity.Admin;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository("adminDao")
public class AdminDaoImpl implements AdminDao {
#Autowired
SessionFactory sessionFactory;
protected Session currentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public void create(Admin admin) {
currentSession().save(admin);
}
#Override
public void update(Admin admin) {
currentSession().update(admin);
}
#Override
public void delete(Long adminId) {
currentSession().delete(adminId);
}
#Override
public Admin edit(Long adminId) {
return find(adminId);
}
#Override
public Admin find(Long adminId) {
return (Admin) currentSession().get(Admin.class, adminId);
}
#Override
public List<Admin> getAll() {
return currentSession().createCriteria(Admin.class).list();
}
}
controller class AdminController.java
package com.finalproject.controller;
import com.finalproject.entity.Admin;
import com.finalproject.service.AdminService;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping(value = "/admin")
public class AdminController {
#Autowired
AdminService adminService;
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String register(Map<String, Object> map) {
map.put("adminReg", new Admin());
return "/admin/add";
}
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(Admin admin, Map<String, Object> map) {
adminService.create(admin);
return "redirect:/admin/details/" + admin.getAdminId();
}
#RequestMapping(value = "/details/{adminId}",method = RequestMethod.GET)
public String details(#PathVariable("adminId") Long adminId, Map<String, Object> map) {
Admin admin = adminService.find(adminId);
map.put("adminName", admin.getAdminName());
map.put("adminEmail", admin.getAdminEmail());
map.put("adminPass", admin.getAdminPass());
return "admin/details";
}
}
Error message
type Exception report
message Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread
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 org.hibernate.HibernateException: No Session found for current thread
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
root cause
org.hibernate.HibernateException: No Session found for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:978)
com.finalproject.dao.impl.AdminDaoImpl.currentSession(AdminDaoImpl.java:19)
com.finalproject.dao.impl.AdminDaoImpl.create(AdminDaoImpl.java:24)
com.finalproject.service.impl.AdminServiceImpl.create(AdminServiceImpl.java:22)
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)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
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:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy125.create(Unknown Source)
com.finalproject.controller.AdminController.create(AdminController.java:29)
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)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
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:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Error Message
AdminDaoImpl.java
I have a big problem with my DAO class, when I want to persist a new entity, I get a NullPointerException from my wildfly-server.
I have a ManagedBean called VeranstaltungAnlegenMB
package de.mb;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import de.awk.veranstaltungsverwaltung.facade.IVeranstaltungsverwaltungFacade;
#ManagedBean(name="veranstaltungAnlegenMB")
#RequestScoped
public class VeranstaltungAnlegenMB {
#EJB
IVeranstaltungsverwaltungFacade veranstaltungsverwaltungFacade;
private String name;
private String bezeichnung;
private String semester;
private int maxTeilnehmer;
public void veranstaltungAnlegen() {
System.out.println("veranstaltungAnlegen() aufgerufen in VeranstaltungAnlegenMB");
this.veranstaltungsverwaltungFacade.getVeranstaltungAnlegen().veranstaltungAnlegen(this.name,
this.bezeichnung, this.maxTeilnehmer, this.semester);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBezeichnung() {
return bezeichnung;
}
public void setBezeichnung(String bezeichnung) {
this.bezeichnung = bezeichnung;
}
public String getSemester() {
return semester;
}
public void setSemester(String semester) {
this.semester = semester;
}
public int getMaxTeilnehmer() {
return maxTeilnehmer;
}
public void setMaxTeilnehmer(int maxTeilnehmer) {
this.maxTeilnehmer = maxTeilnehmer;
}
}
The ManagedBean has a method veranstaltungAnlegen(), there I call my class VeranstaltungsverwaltungFacade (a stateless bean), it implements an local bean interface. The class VeranstaltungsverwaltungFacade hold my use cases. My use cases are all stateless beans and implements local bean interfaces too.
Here you see one of my use case class.
package de.awk.veranstaltungsverwaltung.usecase.impl;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import de.awk.veranstaltungsverwaltung.dao.VeranstaltungDAO;
import de.awk.veranstaltungsverwaltung.model.Veranstaltung;
import de.awk.veranstaltungsverwaltung.usecase.ILehrveranstaltungAnlegen;
#Stateless
public class LehrveranstaltungAnlegenImpl implements ILehrveranstaltungAnlegen {
#EJB
private VeranstaltungDAO veranstaltungDAO;
public LehrveranstaltungAnlegenImpl() {
}
#Override
public void veranstaltungAnlegen(String name, String bezeichnung, int maxTeilnehmer, String semester) {
System.out.println(toString() + " starte Methode veranstaltungAnlegen(...)");
Veranstaltung aVeranstaltung = new Veranstaltung(name, bezeichnung, maxTeilnehmer, semester);
System.out.println("Veranstaltung: " + aVeranstaltung.getV_name() + " erstellt");
veranstaltungDAO.save(aVeranstaltung);
System.out.println(toString() + " veranstaltungAnlegen(String name, String bezeichnung, "
+ "int maxTeilnehmer, String semester)");
}
#Override
public String toString() {
return "LehrveranstaltungAnlegenImpl";
}
}
My use case has my DAO class. When I try to save/persist my new entity I get a NullPointerException. I debugged my program and found out that my variable veranstaltungDAO has not been initialized --> null. But I don't know why, because I see in my console that the VeranstaltungDAO is deployed.
'[org.jboss.as.ejb3.deployment] (MSC service thread 1-4) WFLYEJB0473: JNDI bindings for session bean named 'VeranstaltungDAO' in deployment...'
Here you can see my DAO class:
import javax.ejb.Stateless;
import de.awk.dao.GenericDAO;
import de.awk.veranstaltungsverwaltung.model.Veranstaltung;
#Stateless
public class VeranstaltungDAO extends GenericDAO<Veranstaltung>{
public VeranstaltungDAO() {
super(Veranstaltung.class);
}
}
Here you see my entity class:
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import java.io.Serializable;
#Entity
#Access(AccessType.FIELD)
public class Veranstaltung implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="V_ID")
#SequenceGenerator(name="V_ID", sequenceName="SEQ_VERANSTALTUNG_ID", allocationSize=1)
private int v_id;
private String v_name;
private String v_bezeichnung;
private int max_Teilnehmer;
private String semester;
#ElementCollection
private List<String> studenten;
private String dozent;
#OneToMany
#JoinTable(name="Veranstaltung_Hausarbeit",
joinColumns=#JoinColumn(name="v_id", referencedColumnName="v_id"),
inverseJoinColumns=#JoinColumn(name="h_id", referencedColumnName="h_id"))
private List<Hausarbeit> hausarbeitenliste;
#OneToMany
#JoinTable(name="Veranstaltung_Dokument",
joinColumns=#JoinColumn(name="v_id", referencedColumnName="v_id"),
inverseJoinColumns=#JoinColumn(name="d_id", referencedColumnName="d_id"))
private List<VeranstaltungDokument> dokumentenliste;
public Veranstaltung() {
}
public Veranstaltung(String v_name, String v_bezeichnung, int max_Teilnehmer, String semester) {
this.v_name = v_name;
this.v_bezeichnung = v_bezeichnung;
this.max_Teilnehmer = max_Teilnehmer;
this.semester = semester;
this.dozent = "bla";
this.hausarbeitenliste = new ArrayList<Hausarbeit>();
this.dokumentenliste = new ArrayList<VeranstaltungDokument>();
this.studenten = new ArrayList<String>();
}
public List<Hausarbeit> getHausarbeitenliste() {
return hausarbeitenliste;
}
public void setHausarbeitenliste(List<Hausarbeit> hausarbeitenliste) {
this.hausarbeitenliste = hausarbeitenliste;
}
public List<VeranstaltungDokument> getDokumentenliste() {
return dokumentenliste;
}
public void setDokumentenliste(List<VeranstaltungDokument> dokumentenliste) {
this.dokumentenliste = dokumentenliste;
}
public List<String> getStudenten() {
return studenten;
}
public void setStudenten(List<String> studenten) {
this.studenten = studenten;
}
public void addStudent(String student) {
this.studenten.add(student);
}
public int getV_id() {
return v_id;
}
public void setV_id(int v_id) {
this.v_id = v_id;
}
public String getV_name() {
return v_name;
}
public void setV_name(String v_name) {
this.v_name = v_name;
}
public String getV_bezeichnung() {
return v_bezeichnung;
}
public void setV_bezeichnung(String v_bezeichnung) {
this.v_bezeichnung = v_bezeichnung;
}
public int getMax_Teilnehmer() {
return max_Teilnehmer;
}
public void setMax_Teilnehmer(int max_Teilnehmer) {
this.max_Teilnehmer = max_Teilnehmer;
}
public String getSemester() {
return semester;
}
public void setSemester(String semester) {
this.semester = semester;
}
public String getDozent() {
return dozent;
}
public void setDozent(String dozent) {
this.dozent = dozent;
}
public void addHausarbeit(Hausarbeit addHausarbeit) {
this.hausarbeitenliste.add(addHausarbeit);
}
}
I hope you guys can help me.
My GenericsDAO which extends my class VeranstaltungDAO
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
public abstract class GenericDAO<T> {
private final static String UNIT_NAME = "EJB_JPA_LearningPortal";
#PersistenceContext(unitName = UNIT_NAME)
private EntityManager em;
private Class<T> entityClass;
public GenericDAO(){}
public GenericDAO(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected void delete(Object id, Class<T> classe) {
T entityToBeRemoved = em.getReference(classe, id);
em.remove(entityToBeRemoved);
}
public T update(T entity) {
return em.merge(entity);
}
public void save(T entity) {
this.em.persist(entity);
}
public T find(int entityID) {
return em.find(entityClass, entityID);
}
// Using the unchecked because JPA does not have a
// em.getCriteriaBuilder().createQuery()<T> method
#SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findAll() {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return em.createQuery(cq).getResultList();
}
// Using the unchecked because JPA does not have a
// ery.getSingleResult()<T> method
#SuppressWarnings("unchecked")
protected T findOneResult(String namedQuery, Map<String, Object> parameters) {
T result = null;
try {
Query query = em.createNamedQuery(namedQuery);
// Method that will populate parameters if they are passed not null and empty
if (parameters != null && !parameters.isEmpty()) {
populateQueryParameters(query, parameters);
}
result = (T) query.getSingleResult();
} catch (Exception e) {
System.out.println("Error while running query: " + e.getMessage());
e.printStackTrace();
}
return result;
}
private void populateQueryParameters(Query query, Map<String, Object> parameters) {
for (Entry<String, Object> entry : parameters.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
}
}
public T findByString(String entityID) {
return em.find(entityClass, entityID);
}
}
Here you can see my stack trace, I don't know how to format it better...
15:15:59,433 WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle] (default task-11) java.lang.NullPointerException: javax.el.ELException: java.lang.NullPointerException
at com.sun.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:187)
at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:814)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.DisableCacheHandler.handleRequest(DisableCacheHandler.java:33)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AuthenticationConstraintHandler.handleRequest(AuthenticationConstraintHandler.java:51)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.servlet.handlers.security.ServletSecurityConstraintHandler.handleRequest(ServletSecurityConstraintHandler.java:56)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:284)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at de.awk.veranstaltungsverwaltung.usecase.impl.LehrveranstaltungAnlegenImpl.veranstaltungAnlegen(LehrveranstaltungAnlegenImpl.java:26)
at de.mb.VeranstaltungAnlegenMB.veranstaltungAnlegen(VeranstaltungAnlegenMB.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:181)
... 44 more
15:15:59,442 SEVERE [javax.enterprise.resource.webcontainer.jsf.context] (default task-11) java.lang.NullPointerException
at de.awk.veranstaltungsverwaltung.usecase.impl.LehrveranstaltungAnlegenImpl.veranstaltungAnlegen(LehrveranstaltungAnlegenImpl.java:26)
at de.mb.VeranstaltungAnlegenMB.veranstaltungAnlegen(VeranstaltungAnlegenMB.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:181)
at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:814)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.DisableCacheHandler.handleRequest(DisableCacheHandler.java:33)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AuthenticationConstraintHandler.handleRequest(AuthenticationConstraintHandler.java:51)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.servlet.handlers.security.ServletSecurityConstraintHandler.handleRequest(ServletSecurityConstraintHandler.java:56)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:284)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
I get the record using primarykey id in amazon dynamodb using java.
AccountController.java
package com.dynamodb.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.account.json.AccountJson;
import com.account.service.AccountService;
#Controller
public class AccountController extends AbstractServiceController {
#Autowired
private AccountService accountService;
#RequestMapping(value = "/deleteAccountByAccountId", method = RequestMethod.POST)
public #ResponseBody String deleteAccountByAccountId(#RequestBody AccountJson accountJson) {
try {
Boolean bool = accountService.deleteAccountByAccountId(accountJson.getAccountId());
if (bool) {
return "Record deleted Successfully";
} else {
return "Record not deleted";
}
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
AccountService.java
package com.account.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.account.dao.AccountRepository;
#Service
public class AccountService {
#Autowired
private AccountRepository accountRepository;
public Boolean deleteAccountByAccountId(String accountId) {
return accountRepository.deleteAccountByAccountId(accountId);
}
}
AccountRepository.java
package com.account.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.account.datastore.Account;
#Repository
public class AccountRepository extends BaseRepository {
public Account getAccountByAccountId(String accountId) {
Account account = null;
try {
DynamoDBMapper mapper = getDynameDbMapper();
DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
scanExpression.addFilterCondition("accountId", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withS(accountId)));
List<Account> accounts = mapper.scan(Account.class, scanExpression);
if (accounts != null && accounts.size() > 0) {
account = accounts.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
return account;
}
public Boolean deleteAccountByAccountId(String accountId) {
try {
Account account = getAccountByAccountId(accountId);
if (account != null) {
DynamoDBMapper mapper = getDynameDbMapper();
mapper.delete(account);
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
Account.java
package com.account.datastore;
import java.io.Serializable;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
#DynamoDBTable(tableName = "cd_accounts")
public class Account implements Serializable {
private static final long serialVersionUID = 244669855912873613L;
#DynamoDBAutoGeneratedKey
#DynamoDBHashKey
private String accountId;
private String documentTypeId;
private String accountName;
private Long isActive;
private Long isBill;
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getDocumentTypeId() {
return documentTypeId;
}
public void setDocumentTypeId(String documentTypeId) {
this.documentTypeId = documentTypeId;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Long getIsActive() {
return isActive;
}
public void setIsActive(Long isActive) {
this.isActive = isActive;
}
public Long getIsBill() {
return isBill;
}
public void setIsBill(Long isBill) {
this.isBill = isBill;
}
}
Error is occurred while deleting the record. How to delete the record in amazon dynamodb using java.
com.amazonaws.AmazonServiceException: The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: NR1SVIM98PVPFNHUOL49EI4JPFVV4KQNSO5AEMVJF66Q9ASUAAJG)
10:02:18,739 ERROR [AccountRepository] deleteAccountByAccountId Error:The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: NR1SVIM98PVPFNHUOL49EI4JPFVV4KQNSO5AEMVJF66Q9ASUAAJG)
10:02:18,739 DEBUG [AccountController] --------------deleteAccountByAccountId----------------END------------------
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1077)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:725)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:460)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:295)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3106)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.deleteItem(AmazonDynamoDBClient.java:967)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.delete(DynamoDBMapper.java:1364)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.delete(DynamoDBMapper.java:1272)
at com.account.dao.AccountRepository.deleteAccountByAccountId(AccountRepository.java:110)
at com.account.service.AccountService.deleteAccountByAccountId(AccountService.java:40)
at com.account.controller.AccountController.deleteAccountByAccountId(AccountController.java:62)
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:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
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:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
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.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
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)
documentTypeId is primarykey for cd_documentTypes table, this primarykey is used in cd_accounts table as a foreignkey.
If the table having foreignkey relation we must mention the #DynamoDBRangeKey annotation above documentTypeId attribute in Account class. Problem is solved after declared the #DynamoDBRangeKey on top of the attribute documentTypeId.
#DynamoDBRangeKey
private String documentTypeId;
If we want to save or update or delete records in amazon dynamodb using java we must mention the
annotation #DynamoDBHashKey on top of the primarykey column.
#DynamoDBAutoGeneratedKey
#DynamoDBHashKey
private String accountId;
Below is the image shown for foreignkey relation exists in cd_accounts table.
Note:Range key attribute field is displayed if the table is mapping to another table primarykey in amaozong dynamodb.
I am using Spring MVC to build a web application. I created a new VO named User and created a POST method to process the VO. The VO is having default constructor, yet I am getting
java.lang.NoSuchMethodException: [Lcom.dn.vo.User;.<init>().
The code involved is as follows:
User VO
package com.dn.vo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.beans.factory.annotation.Autowired;
import com.dn.enums.Salutation;
#Entity
#Table(name = "PHONE_USER")
public class User implements Serializable {
long userId;
String firstName;
String surName;
Salutation salutation;
public User() {
super();
}
public User(long userId, String firstName, String surName, Salutation salutation) {
super();
this.userId = userId;
this.firstName = firstName;
this.surName = surName;
this.salutation = salutation;
}
#Id
#GeneratedValue
#Column(name = "USER_ID", unique = true, nullable = false, precision = 5, scale = 0)
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
#Column(name = "FIRST_NAME", nullable = false, length = 20)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "SURNAME", nullable = false, length = 20)
public String getSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
#Column(name = "SALUTATION", nullable = false, length = 20)
public Salutation getSalutation() {
return salutation;
}
public void setSalutation(Salutation salutation) {
this.salutation = salutation;
}
#Override
public String toString() {
return firstName+" "+surName;
}
}
MVC Controller
package com.dn.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dn.db.DBConnectionProvider;
import com.dn.vo.User;
#Controller
public class UserRegistrationController {
#Autowired
private DBConnectionProvider dbConnectionProvider;
#ResponseBody #RequestMapping(value= "/createUser", method = RequestMethod.POST, headers="Accept=application/json")
public void createUser( User user) {
System.out.println(user.toString());
}
#ResponseBody #RequestMapping(value= "/createUsers", method = RequestMethod.POST, headers="Accept=application/json")
public void createUser( User[] user) {
System.out.println(user.toString());
}
}
HTTP Client Test
package com.dn.controller;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jackson.map.ObjectMapper;
import com.dn.enums.Salutation;
import com.dn.vo.User;
public class UserRegistrationControllerTest {
public static void main(String[] args) {
UserRegistrationControllerTest test = new UserRegistrationControllerTest();
test.testUserArrayInput();
}
private void testSingleUserInput(){
HttpClient httpClient = null;
try {
httpClient = new DefaultHttpClient();
String url = "http://localhost:8080/DNServer/createUser";
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(new BasicHeader("Accept", "application/json"));
User region = new User();
region.setFirstName("ABC");
region.setSurName("XYZ");
region.setSalutation(Salutation.Mr);
ObjectMapper mapper = new ObjectMapper();
System.out.println( mapper.writeValueAsString(region));
List nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("user", mapper.writeValueAsString(region)));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
System.out.println("test Single User Input done"+response);
} catch (Exception e) {
e.printStackTrace();
}
}
private void testUserArrayInput(){
HttpClient httpClient = null;
try {
httpClient = new DefaultHttpClient();
String url = "http://localhost:8080/DNServer/createUsers";
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(new BasicHeader("Accept", "application/json"));
User[] regions = new User[1];
User region = new User();
region.setFirstName("XYZ");
region.setSurName("ABC");
region.setSalutation(Salutation.Mr);
regions[0] = region;
ObjectMapper mapper = new ObjectMapper();
System.out.println( mapper.writeValueAsString(regions));
List nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("users", mapper.writeValueAsString(regions)));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
System.out.println("done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Full Stack Trace
SEVERE: Servlet.service() for servlet [DNServlet] in context with path [/DNServer] threw exception [Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [[Lcom.dn.vo.User;]: No default constructor found; nested exception is java.lang.NoSuchMethodException: [Lcom.dn.vo.User;.<init>()] with root cause
java.lang.NoSuchMethodException: [Lcom.dn.vo.User;.<init>()
at java.lang.Class.getConstructor0(Class.java:2721)
at java.lang.Class.getDeclaredConstructor(Class.java:2002)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:105)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:81)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:104)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:79)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:157)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:124)
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.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1017)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
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)`enter code here`
I think that the clue is in the method name:
[Lcom.dn.vo.User;.<init>()
When we deconstruct that, Spring appears to be trying to invoke a no-args constructor (the <init>() "method") on the type [Lcom.dn.vo.User;. But that type means "array of com.dn.vo.User". And array classes don't have constructors.
I can see some code in your unit test that creates a User[] and appears to pass it as an argment in a POST request to "/createUsers". But the MVC class doesn't have a method that binds to "/createUsers".
Is that right???
Java Student here working on a basic Hibernate project.
Server :tomcat
IDE : Eclipse Juno
I'm trying to persist some data into mySql Db but i've been getting an error every time I click the process button.
The error: org.hibernate.exception.SQLGrammarException: Table 'timdowney.requestdatapersistent' doesn't exist
The name of my DB is : timdowney and it DOES exist.
My Db server works fine because i've tested it with other jdbc apps.
So, my question is: why am i getting an error stating that Table 'timdowney.requestdatapersistent' doesn't exist while timdowney is not a table but my DB name ?
fyi: requestdatapersistent is a my bean class
It's a large code, i agree.
Button Method Error
org.hibernate.exception.SQLGrammarException: Table 'timdowney.requestdatapersistent' doesn't exist
java.lang.reflect.InvocationTargetException
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 shared.HelperBaseCh4.invokeButtonMethod(HelperBaseCh4.java:155)
at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:124)
at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:133)
at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:100)
at ch5.persistentData.ControllerHelper.doPost(ControllerHelper.java:128)
at ch5.persistentData.configure.ControllerHelper.doPost(ControllerHelper.java:40)
at ch5.persistentData.configure.Controller.doPost(Controller.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.exception.SQLGrammarException: Table 'timdowney.requestdatapersistent' doesn't exist
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy18.executeQuery(Unknown Source)
at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1469)
at org.hibernate.engine.internal.StatefulPersistenceContext.getDatabaseSnapshot(StatefulPersistenceContext.java:301)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:217)
at org.hibernate.event.internal.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:495)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:641)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:633)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:629)
at shared.HibernateHelper.updateDB(HibernateHelper.java:135)
at ch5.persistentData.ControllerHelper.processMethod(ControllerHelper.java:101)
... 29 more
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'timdowney.requestdatapersistent' doesn't exist
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2934)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1616)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1708)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3255)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1293)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1428)
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.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 42 more
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/timdowney</property>
<property name="connection.username">root</property>
<property name="connection.password">pasapas2005</property>
<property name="c3p0.min_size">1</property>
<property name="c3p0.max_size">5</property>
<property name="c3p0.timeout">300</property>
<property name="c3p0.max_statements">50</property>
<property name="c3p0.idle_test_period">300</property>
</session-factory>
</hibernate-configuration>
My Bean Class
package ch5.persistentData;
import java.io.Serializable;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
#Entity
public class RequestDataPersistent extends shared.PersistentBase implements
Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
protected String hobby;
protected String aversion;
private Long id;
public RequestDataPersistent() {
}
#Id
public Long getId() {
return id;
}
protected void setId(Long id) {
this.id = id;
}
#Pattern(regexp = ".*\\S.*", message = "cannot be empty")
#NotNull
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
#Pattern(regexp = ".*\\S.*", message = "cannot be empty")
#NotNull
public String getAversion() {
return aversion;
}
public void setAversion(String aversion) {
this.aversion = aversion;
}
protected int daysPerWeek;
#Min(value = 1, message = "must be greater than 1, if this is a hobby.")
#Max(value = 7, message = "cannot be greater than 7. A week only has 7 days.")
public int getDaysPerWeek() {
return daysPerWeek;
}
public void setDaysPerWeek(int daysPerWeek) {
this.daysPerWeek = daysPerWeek;
}
}
Controller helper class
package ch5.persistentData.configure;
import ch5.persistentData.RequestDataPersistent;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import shared.HibernateHelper;
public class ControllerHelper
extends ch5.persistentData.ControllerHelper {
public ControllerHelper(
HttpServlet servlet,
HttpServletRequest request,
HttpServletResponse response) {
super(servlet, request, response);
}
static public void initHibernate(HttpServlet servlet) {
boolean create =
Boolean.parseBoolean(servlet.getInitParameter("create"));
if (create) {
HibernateHelper.createTable(RequestDataPersistent.class);
}
HibernateHelper.initSessionFactory(RequestDataPersistent.class);
}
#Override
public void doGet()
throws ServletException, java.io.IOException
{
super.doGet();
}
#Override
public void doPost()
throws ServletException, java.io.IOException
{
super.doPost();
}
}
HiernateHelper class
package shared;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.criterion.Restrictions;
public class HibernateHelper {
static protected Logger log = Logger
.getLogger("bytesizebook.webdev.hibernate");
static protected List<Class> listClasses = new ArrayList<Class>();
static protected SessionFactory sessionFactory;
static public void initSessionFactory(Properties props, Class... mappings) {
if (addMappings(listClasses, mappings)) {
closeSessionFactory(sessionFactory);
sessionFactory = createFactory(props, listClasses);
}
}
static public void initSessionFactory(Class... mappings) {
initSessionFactory(null, mappings);
}
static public void createTable(Properties props, Class... mappings) {
List<Class> tempList = new ArrayList<Class>();
SessionFactory tempFactory = null;
addMappings(tempList, mappings);
if (props == null) {
props = new Properties();
}
props.setProperty(Environment.HBM2DDL_AUTO, "create");
tempFactory = createFactory(props, tempList);
closeSessionFactory(tempFactory);
}
static public void createTable(Class... mappings) {
createTable(null, mappings);
}
static protected boolean addMappings(List<Class> list, Class... mappings) {
boolean bNewClass = false;
for (Class mapping : mappings) {
if (!list.contains(mapping)) {
list.add(mapping);
bNewClass = true;
}
}
return bNewClass;
}
static protected SessionFactory createFactory(Properties props,
List<Class> list) {
SessionFactory factory = null;
Configuration cfg = new Configuration();
try {
if (props != null) {
cfg.addProperties(props);
}
configureFromFile(cfg);
for (Class mapping : list) {
cfg.addAnnotatedClass(mapping);
}
factory = buildFactory(cfg);
} catch (Exception ex) {
// Make sure you log the exception, as it might be swallowed
log.error("SessionFactory creation failed.", ex);
closeSessionFactory(factory);
factory = null;
// hibernate has a runtime exception for handling problems with
// initialisation. Cast the ex to HibernateException and raise,
// since the root problem is a Hibernate problem.
throw new HibernateException(ex);
}
return factory;
}
static protected void configureFromFile(Configuration cfg) {
try {
cfg.configure();
} catch (HibernateException ex) {
if (ex.getMessage().equals("/hibernate.cfg.xml not found")) {
log.warn(ex.getMessage());
} else {
log.error("Error in hibernate " + "configuration file.", ex);
throw ex;
}
}
}
static protected SessionFactory buildFactory(Configuration cfg)
throws Exception {
SessionFactory factory = null;
try {
factory = cfg.buildSessionFactory();
} catch (Exception ex) {
closeSessionFactory(factory);
factory = null;
throw ex;
}
return factory;
}
static public void closeSessionFactory(SessionFactory factory) {
if (factory != null) {
factory.close();
}
}
static public void closeFactory() {
closeSessionFactory(sessionFactory);
}
static public void updateDB(Object obj) {
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(obj);
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
}
static public void updateDB(java.util.List list) {
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
for (Object obj : list) {
session.saveOrUpdate(obj);
}
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
}
static public void saveDB(Object obj) {
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(obj);
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
}
static public void removeDB(Object obj) {
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.delete(obj);
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
}
static public java.util.List getListData(Class classBean, String strKey,
Object value) {
java.util.List result = new java.util.ArrayList();
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Criteria criteria = session.createCriteria(classBean);
if (strKey != null) {
criteria.add(Restrictions.like(strKey, value));
}
result = criteria.list();
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
return result;
}
static public java.util.List getListData(Class classBean, String strKey1,
Object value1, String strKey2, Object value2) {
java.util.List result = new java.util.ArrayList();
boolean withParent = false;
int age = 0;
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Criteria criteria = session.createCriteria(classBean);
if (strKey1 != null) {
criteria.add(Restrictions.like(strKey1, value1));
}
if (strKey2 != null) {
criteria.add(Restrictions.like(strKey2, value2));
}
result = criteria.list();
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
return result;
}
static public java.util.List getListData(Class classBean) {
return getListData(classBean, null, null);
}
static public Object getFirstMatch(Class classBean, String strKey,
Object value) {
Object result = null;
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Criteria criteria = session.createCriteria(classBean);
if (strKey != null) {
criteria.add(Restrictions.like(strKey, value));
}
criteria.setMaxResults(1);
result = criteria.uniqueResult();
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
return result;
}
static public Object getFirstMatch(Object data, String strKey, Object value) {
return getFirstMatch(data.getClass(), strKey, value);
}
static public Object getKeyData(Class beanClass, long itemId) {
Object data = null;
Session session = sessionFactory.openSession();
data = session.get(beanClass, itemId);
session.close();
return data;
}
static public boolean isSessionOpen() {
return sessionFactory != null;
}
}
new stacktrace after adding #Table annotation in my bean class
Button Method Error
org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of ch5.persistentData.RequestDataPersistent.id
java.lang.reflect.InvocationTargetException
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 shared.HelperBaseCh4.invokeButtonMethod(HelperBaseCh4.java:155)
at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:124)
at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:133)
at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:100)
at ch5.persistentData.ControllerHelper.doPost(ControllerHelper.java:128)
at ch5.persistentData.configure.ControllerHelper.doPost(ControllerHelper.java:40)
at ch5.persistentData.configure.Controller.doPost(Controller.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of ch5.persistentData.RequestDataPersistent.id
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:119)
at org.hibernate.mapping.Component$ValueGenerationPlan.execute(Component.java:436)
at org.hibernate.id.CompositeNestedGeneratedValueGenerator.generate(CompositeNestedGeneratedValueGenerator.java:121)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:118)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:641)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:633)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:629)
at shared.HibernateHelper.updateDB(HibernateHelper.java:130)
at ch5.persistentData.ControllerHelper.processMethod(ControllerHelper.java:101)
... 29 more
Caused by: java.lang.IllegalArgumentException: argument type mismatch
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.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:65)
... 41 more
org.hibernate.exception.SQLGrammarException: Table 'timdowney.requestdatapersistent' doesn't exist
Error says schemaname.tablename does not exist, so your schema is timdowney and table name is requestdatapersistent. Since you did not specify any table in Entity it is using bean name as entity name, you need to do either of following:
Create a table named requestdatapersistent
If there is a different table name then provide in annotation using following:
#Entity
#Table(name="request_data_persistent")
Hoping this solves your problem.
Cheers !!
if annotation doesn't work for you, you may try creating hibernate mapping file similar to the below:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="ch5.persistentData.RequestDataPersistent"
table="tablename" catalog="timdowney ">
<id name="ID" type="java.lang.Long">
<column name="id" length="10" not-null="true" unique="true" />
</id>
<property name="EventName" type="String">
<column name="eventname" length="10" not-null="true" unique="false" />
</property>
<property name="hobby" type="String">
<column name="hobby" length="20" not-null="true"
unique="false" />
</property>
....and so on
</class>
</hibernate-mapping>