unknown service requested exception with hibernate - java

Throwing unknown service Exception while opening session in getCourses method in DAO implementation.it works fine when it gets input from backend but when I call it from UI it is throwing this exception
hibernate.cfg.xml
`
<!-- hibernate dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#10.123.79.59:1521:georli04</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- Automatic schema creation (begin) === -->
<property name="hibernate.hbm2ddl.auto">none</property>
<!-- Simple memory-only cache -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<mapping class="com.infy.entity.StudentEntity"/>
<mapping class="com.infy.entity.CourseEntity"/>
`
DAO implementation Exception occurs when we try to open session in getCourses method
public class StudentDAOImpl implements StudentDAO {
public Student getStudentDetails(String studentId) throws Exception {
SessionFactory sessionFactory = null;
Session session = null;
Student student = null;
try {
sessionFactory = HibernateUtility.createSessionFactory();
session = sessionFactory.openSession();
StudentEntity se = (StudentEntity) session.get(StudentEntity.class,
studentId);
if (se != null) {
student = new Student();
student.setStudentId(se.getStudentId());
student.setDateOfBirth(se.getDateOfBirth());
System.out.println(se.getDateOfBirth());
student.setStudentName(se.getStudentName());
System.out.println(se.getStudentName());
student.setBranch(se.getBranch());
student.setSem(se.getSem());
student.setEmail(se.getEmail());
}
} catch (HibernateException exception) {
exception.printStackTrace();
DOMConfigurator.configure("src/resources/log4j.xml");
Logger logger = Logger.getLogger(this.getClass());
logger.error(exception.getMessage(), exception);
throw new Exception("DAO.TECHNICAL_ERROR");
} catch (Exception exception) {
exception.printStackTrace();
DOMConfigurator.configure("src/resources/log4j.xml");
Logger logger = Logger.getLogger(this.getClass());
logger.error(exception.getMessage(), exception);
throw exception;
} finally {
if (session.isOpen() || session != null) {
session.close();
}
}
return student;
}
#SuppressWarnings("unchecked")
public List<Course> getCourses(int semester) throws Exception {
SessionFactory sessionFactory = HibernateUtility.createSessionFactory();
Session session = null;
List<CourseEntity> courseEntities = new LinkedList<CourseEntity>();
List<Course> courses = new LinkedList<Course>();
String hql = "from CourseEntity ce where ce.semester='" + semester
+ "'";
try {
System.out.println("before session");
session = sessionFactory.openSession();
System.out.println("after session");
Query q = session.createQuery(hql);
courseEntities = q.list();
if (courseEntities.isEmpty())
System.out.println("empty");
for (CourseEntity i : courseEntities) {
Course course = new Course();
course.setCourseId(i.getCourseId());
course.setCourseName(i.getCourseName());
course.setCourseType(i.getCourseType());
course.setSemester(i.getSemester());
course.setBranch(i.getBranch());
courses.add(course);
}
} catch (HibernateException exception) {
exception.printStackTrace();
DOMConfigurator.configure("src/resources/log4j.xml");
Logger logger = Logger.getLogger(this.getClass());
logger.error(exception.getMessage(), exception);
throw new Exception("DAO.TECHNICAL_ERROR");
} catch (Exception exception) {
exception.printStackTrace();
DOMConfigurator.configure("src/resources/log4j.xml");
Logger logger = Logger.getLogger(this.getClass());
logger.error(exception.getMessage(), exception);
throw exception;
}finally {
if (session.isOpen() || session != null)
session.close();
}
return courses;
}
exception
org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.engine.jdbc.connections.spi.ConnectionProvider]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:201)
at org.hibernate.internal.AbstractSessionImpl.getJdbcConnectionAccess(AbstractSessionImpl.java:341)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.<init>(JdbcCoordinatorImpl.java:114)
at org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl.<init>(TransactionCoordinatorImpl.java:89)
at org.hibernate.internal.SessionImpl.<init>(SessionImpl.java:258)
at org.hibernate.internal.SessionFactoryImpl$SessionBuilderImpl.openSession(SessionFactoryImpl.java:1589)
at org.hibernate.internal.SessionFactoryImpl.openSession(SessionFactoryImpl.java:999)
at com.infy.dao.StudentDAOImpl.getCourses(StudentDAOImpl.java:74)
at com.infy.service.StudentServiceImpl.getListOfCourses(StudentServiceImpl.java:73)
at com.infy.api.RegistrationAPI.getCoursesList(RegistrationAPI.java:38)
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.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:317)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:298)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
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: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:957)
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:316)
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)

Try using a DB connection provider, like c3p0,
Add to pom.xml
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.2.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.6.Final</version>
</dependency>
And add these line into hibernate.cfg.xml
<property name= "hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.acquire_increment">5</property>
<property name="hibernate.c3p0.idle_test_period">1800</property>
<property name="hibernate.c3p0.max_size">600</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.timeout">1800</property>

Related

java.sql.SQLException: System or internal error java.io.IOException on connect to database

I am having a random problem that when performing the connection with informix the following error occurs:
java.sql.SQLException: System or internal error java.io.IOException
at com.informix.util.IfxErrMsg.getSQLException(Unknown Source)
at com.informix.jdbc.IfxSqli.handleSocketException(Unknown Source)
at com.informix.jdbc.IfxSqli.receiveMessage(Unknown `enter code here`Source)
at com.informix.jdbc.IfxSqli.executePrepare(Unknown Source)
at com.informix.jdbc.IfxPreparedStatement.setupExecutePrepare(Unknown Source)
at com.informix.jdbc.IfxPreparedStatement.processSQL(Unknown Source)
at com.informix.jdbc.IfxPreparedStatement.<init>(Unknown Source)
at com.informix.jdbc.IfxSqliConnect.createPreparedStmt(Unknown Source)
at com.informix.jdbc.IfxSqliConnect.prepareStatement(Unknown Source)
at org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.prepareStatement(DelegatingConnection.java:291)
at org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.prepareStatement(DelegatingConnection.java:291)
at br.com.solcast.integrador.dao.sisdia.PedidoVendaDAO.carregar(PedidoVendaDAO.java:169)
at br.com.solcast.integrador.service.sisdia.PedidoVendaService.carregar(PedidoVendaService.java:99)
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.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at br.com.solcast.integrador.security.RestAuthenticationFilter.doFilter(RestAuthenticationFilter.java:43)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(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)
Caused by: java.io.IOException
at com.informix.asf.IfxDataInputStream.readFully(Unknown Source)
at com.informix.asf.IfxDataInputStream.readSmallInt(Unknown Source)
... 61 more
My class that connects
public class DAOManager {
private DataSource src;
private Connection con;
public void open() throws SQLException {
try {
if(this.con==null || this.con.isClosed())
this.con = src.getConnection();
} catch(SQLException e) { throw e; }
}
public void close() throws SQLException {
try {
if(this.con!=null && !this.con.isClosed()) {
this.con.close();
this.con = null;
}
} catch(SQLException e) {
throw e;
} finally {
if (this.con != null) {
try { this.con.close(); } catch (SQLException e) { ; }
this.con = null;
}
}
}
public DAOManager() throws NamingException {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
this.src = (DataSource)envContext.lookup("jdbc/cortex-sisdia");
}
public Object gerarDAO(DAO dao) throws SQLException
{
if (this.con == null || this.con.isClosed())
this.open();
switch (dao) {
case AGENDAMENTOOFICINA:
return new AgendamentoOficinaDAO(this.con);
case ESTOQUE:
return new EstoqueDAO(this.con);
case PEDIDOVENDA:
return new PedidoVendaDAO(this.con);
case PESSOA:
return new PessoaDAO(this.con);
case VEICULO:
return new AgendamentoOficinaDAO(this.con);
default:
return null;
}
}
#Override
protected void finalize()
{
try{
this.close();
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
super.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
After instantiating a new connection and executing a prepareStatement the error occurs randomly.

Hibernate NESTED EXCEPTION

I have a problem with hibernate NESTED EXCEPTION. Couple of hours after deploying the app on server, these errors start showing up. I think the problem is with mysql connection which expires. Tomcat 7, show me that application has memory leaks too.
Sample dao class(sometimes app have orm query, sometimes sqlquery)
public List<Object[]> getPckey(String labId){
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try{
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
tx = session.beginTransaction();
String asd = "SELECT pcKey, regDate, pcKeyStatus, unRegDate FROM PcKey WHERE idLaboratory = :laboratoryId AND pcKey IS NOT NULL ORDER BY pcKeyStatus DESC, unRegDate";
Query query = session.createQuery(asd);
query.setParameter("laboratoryId", labId);
List<Object[]> results = query.list();
tx.commit();
return results;
}catch(Exception e){
e.printStackTrace();
return null;
} finally {
if (session != null) {
session.close();
}
}
}
HibernateAnnotationUtil class
public class HibernateAnnotationUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate-annotation.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
Stacktrace
** BEGIN NESTED EXCEPTION ** java.net.SocketException MESSAGE: Connection reset STACKTRACE: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:113)
at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:160)
at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:188)
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1960)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2375)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2874)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1623)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1715)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3249)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1268)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1403)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2065)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:909)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:353)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1873)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:311)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:141)
at com.want.ecdlejb.dao.CheckIsPcExistDao.isPcExist(CheckIsPcExistDao.java:32)
at com.want.ecdlejb.services.CheckIsPcExistService.isPcExist(CheckIsPcExistService.java:18)
at com.want.ecdlwar.computers.CheckIsPcExist.isPcExist(CheckIsPcExist.java:17)
at com.want.ecdlwar.rest.server.Rest.checkIsPcExist(Rest.java:139)
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 com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484)
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) ** END NESTED EXCEPTION **
Configure C3P0 Connection Pool
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myschema</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">3000</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
. . . .
</session-factory>
OR use Apache DBCP Connection Pool
For details about Connection Pooling you can read this Hibernate: What is the connection pool and why is the default one unsuitable for production?
According to stack trace, your dao is throwing an exception :
at
com.want.ecdlejb.dao.CheckIsPcExistDao.isPcExist(CheckIsPcExistDao.java:32)
And as is see, in getPcKey() method, when exception occurs, you only print stack trace in catch block, you have to rollback your transaction here tx.rollback() (in your catch block), otherwise, this will lead to connection leak.
You should also (as suggest below) think to use a connection pool and configure it correctly.
I hope that this could help !
Regards

javax.persistence.PersistenceException: Unable to build entity manager factory org.hibernate.engine.jndi.JndiException: Unable to lookup JNDI name

Hi i am Creating my webservices and for data access i have used JPA(Hibernate), mysql and Glassfish server inside Netbeans IDE.
I am getting following exceptions while accessing:
**Client Side logs :**
----------------------
javax.persistence.PersistenceException: Unable to build entity manager factory org.hibernate.engine.jndi.JndiException: Unable to lookup JNDI name
javax.naming.NamingException: Lookup failed for hrdb;
in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming}
[Root exception is javax.naming.NameNotFoundException: hrdb not found]
**Server side logs**
--------------------
Warning: StandardWrapperValve[com.mycompany.fkemployeeservices.ApplicationConfig]: Servlet.service() for servlet com.mycompany.fkemployeeservices.ApplicationConfig threw exception
javax.naming.NameNotFoundException: hrdb not found
at com.sun.enterprise.naming.impl.TransientContext.doLookup(TransientContext.java:237)
at com.sun.enterprise.naming.impl.TransientContext.lookup(TransientContext.java:204)
at com.sun.enterprise.naming.impl.SerialContextProviderImpl.lookup(SerialContextProviderImpl.java:66)
at com.sun.enterprise.naming.impl.LocalSerialContextProviderImpl.lookup(LocalSerialContextProviderImpl.java:114)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:478)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:622)
at javax.naming.InitialContext.lookup(InitialContext.java:421)
at javax.naming.InitialContext.lookup(InitialContext.java:421)
at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:114)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:115)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:399)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:73)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at entitycontrollers.ControllerFactory.getController(ControllerFactory.java:30)
at data.EmployeeDetailsOperations.<init>(EmployeeDetailsOperations.java:24)
at com.mycompany.fkemployeeservices.FKServicesCentralResource.getEmployeeDetails(FKServicesCentralResource.java:38)
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.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:195)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:387)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:103)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1028)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:372)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
Controller factory
package entitycontrollers;
import javax.persistence.Persistence;
public class ControllerFactory {
public static EvaEmpDetailsJpaController getController() {
return new EvaEmpDetailsJpaController(Persistence.createEntityManagerFactory("com.mycompany_FKEmployeeServices_war_1.0-SNAPSHOTPU"));
}
}
Entity Controllers
package entitycontrollers;
import dbentity.EvaEmpDetails;
import ApplicationSpecificClasses.exceptions.NonexistentEntityException;
import ApplicationSpecificClasses.exceptions.PreexistingEntityException;
import ApplicationSpecificClasses.exceptions.RollbackFailureException;
//import dbentity.EvaEmpDetails;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
/**
*
* #author mukul.kumar
*/
public class EvaEmpDetailsJpaController implements Serializable {
public EvaEmpDetailsJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EvaEmpDetailsJpaController(EntityManagerFactory createEntityManagerFactory) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
this.emf = createEntityManagerFactory;
}
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(EvaEmpDetails evaEmpDetails) throws PreexistingEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(evaEmpDetails);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
if (findEvaEmpDetails(evaEmpDetails.getId()) != null) {
throw new PreexistingEntityException("EvaEmpDetails " + evaEmpDetails + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(EvaEmpDetails evaEmpDetails) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
evaEmpDetails = em.merge(evaEmpDetails);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Long id = evaEmpDetails.getId();
if (findEvaEmpDetails(id) == null) {
throw new NonexistentEntityException("The evaEmpDetails with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Long id) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
EvaEmpDetails evaEmpDetails;
try {
evaEmpDetails = em.getReference(EvaEmpDetails.class, id);
evaEmpDetails.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The evaEmpDetails with id " + id + " no longer exists.", enfe);
}
em.remove(evaEmpDetails);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<EvaEmpDetails> findEvaEmpDetailsEntities() {
return findEvaEmpDetailsEntities(true, -1, -1);
}
public List<EvaEmpDetails> findEvaEmpDetailsEntities(int maxResults, int firstResult) {
return findEvaEmpDetailsEntities(false, maxResults, firstResult);
}
private List<EvaEmpDetails> findEvaEmpDetailsEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(EvaEmpDetails.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public EvaEmpDetails findEvaEmpDetails(Long id) {
EntityManager em = getEntityManager();
try {
return em.find(EvaEmpDetails.class, id);
} finally {
em.close();
}
}
public int getEvaEmpDetailsCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<EvaEmpDetails> rt = cq.from(EvaEmpDetails.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
Please comment for any other required files i need to put here.
In the pom.xml file dependencies of unknown.binary were created.
<dependency>
<groupId>unknown.binary</groupId>
<artifactId>hibernate-jpamodelgen-4.3.1.Final</artifactId>
<version>SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>unknown.binary</groupId>
<artifactId>mysql-connector-java-5.1.23-bin</artifactId>
<version>SNAPSHOT</version>
</dependency>
<dependency>
<groupId>unknown.binary</groupId>
<artifactId>hibernate-jpamodelgen-4.3.1.Final</artifactId>
<version>SNAPSHOT</version>
<scope>provided</scope>
</dependency>
On removing these dependencies Unable to build entity manager factory error is removed.

java.lang.NullPointerException in spring datasource

I done the database table in MySql . I want connection between spring application and database .
For example , i am inserting value in edit-text it could be saved in Database(MySql)
But i got the error . I am new for spring , please need help .
Following is my error log.
16:05:44,784 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/SpringSample].[mvc-dispatcher]] (http-localhost/127.0.0.1:8080-1) Servlet.service() for servlet mvc-dispatcher threw exception: java.lang.NullPointerException
at com.rxoffice.test.controller.JDBCStudentDAO.findByStudentId(JDBCStudentDAO.java:65) [classes:]
at com.rxoffice.test.controller.Home.hi(Home.java:33) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_32]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [rt.jar:1.6.0_32]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [rt.jar:1.6.0_32]
at java.lang.reflect.Method.invoke(Method.java:597) [rt.jar:1.6.0_32]
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:734) [jboss-servlet-api_3.0_spec-1.0.1.Final.jar:1.0.1.Final]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.1.Final.jar:1.0.1.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.17.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.17.Final.jar:]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.17.Final.jar:]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.17.Final.jar:]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:165) [jboss-as-web-7.1.3.Final.jar:7.1.3.Final]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.17.Final.jar:]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.17.Final.jar:]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.17.Final.jar:]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:372) [jbossweb-7.0.17.Final.jar:]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.17.Final.jar:]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:679) [jbossweb-7.0.17.Final.jar:]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:931) [jbossweb-7.0.17.Final.jar:]
at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_32]
following are my files .
JDBCStudentDAO.java -
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
public class JDBCStudentDAO implements StudentDAO {
/*#Autowired
DataSource dataSource;*/
private DataSource dataSource;
JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public void insert(Student student) {
// TODO Auto-generated method stub
String sql = "INSERT INTO student_info " + "(id , name) VALUES (?, ?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, student.getId());
ps.setString(2, student.getName());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
#Override
public Student findByStudentId(int stdId) {
// TODO Auto-generated method stub
String sql = "SELECT * FROM student_info WHERE id = ?";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, stdId);
Student student = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
student = new Student(
rs.getInt("id"),
rs.getString("name")
);
}
rs.close();
ps.close();
return student;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
As you mention in the comments, the error occurs at dataSource.getConnection() - meaning that dataSource is null. You have commented out autowiring that bean, so you're probably forgetting to explicitly setting it:
/*#Autowired DataSource dataSource;*/
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
The relevant parts of your applicationContext.xml file might shed more light on the problem - you might need
<context:annotation-config/>
<context:component-scan base-package="com.whatever.jdbc... , more.packages.to.scan,..."/>
or an explicit <property name="dataSource" ref="..." /> on the JDBCStudentDao bean XML config.
Cheers,
As stated in the comments, DataSource is null. The reason for that is that it hasn't been injected. To fix this, do the following:
1) Make sure JDBCStudentDAO is loaded by spring (applicationContext.xml should be loaded by whatever means, wither by explicitly loading the context or declaration in web.xml)
2) Make Sure DataSource is initialized in your applicationContext.xml or remove the comment before #Autowired
When you start your application, you should see messages that indicate that your datasource is bound (to the database configured in your applicationContext.xml) and that your DAO and entities have been loaded.

Session Factory in Spring and Hibernate

I'm new to Spring MVC and Hibernate and I'm having a problem with my session configurations. I have done this by using the hibernate. What I want to do now is that the sessionFactory will be autowired in the DAO.
This is the application-context.xml -----------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Enable #Controller annotation support -->
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<!-- Map simple view name such as "test" into /WEB-INF/test.jsp -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/jsp" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- Scan classpath for annotations (eg: #Service, #Repository etc) -->
<context:component-scan base-package="com.nutsaboutcandywebproject.controller"/>
<!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
username root and blank password. Change below if it's not the case -->
<bean id="myDataSource" 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/db_nutsaboutcandy"/>
<property name="username" value="root"/>
<property name="password" value=""/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<!-- Hibernate Session Factory -->
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<list>
<value>com.nutsaboutcandywebproject.model</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
This is the full stacktrace.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shoppingCartController' defined in file [C:\Users\Jeremy Marvin\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\NutsAboutCandyWebProject\WEB-INF\classes\com\nutsaboutcandywebproject\controller\ShoppingCartController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.nutsaboutcandywebproject.controller.ShoppingCartController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1279)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1192)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
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.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
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.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.nutsaboutcandywebproject.controller.ShoppingCartController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:164)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069)
... 34 more
Caused by: java.lang.NullPointerException
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getCurrentSession(SQLProductsDataAccess.java:24)
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getInventory(SQLProductsDataAccess.java:35)
at com.nutsaboutcandywebproject.service.ServiceFacadeImpl.getAllProducts(ServiceFacadeImpl.java:140)
at com.nutsaboutcandywebproject.controller.ShoppingCartController.<init>(ShoppingCartController.java:35)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
... 36 more
Apr 04, 2014 1:30:44 AM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shoppingCartController' defined in file [C:\Users\Jeremy Marvin\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\NutsAboutCandyWebProject\WEB-INF\classes\com\nutsaboutcandywebproject\controller\ShoppingCartController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.nutsaboutcandywebproject.controller.ShoppingCartController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1279)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1192)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
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.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
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.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.nutsaboutcandywebproject.controller.ShoppingCartController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:164)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069)
... 34 more
Caused by: java.lang.NullPointerException
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getCurrentSession(SQLProductsDataAccess.java:24)
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getInventory(SQLProductsDataAccess.java:35)
at com.nutsaboutcandywebproject.service.ServiceFacadeImpl.getAllProducts(ServiceFacadeImpl.java:140)
at com.nutsaboutcandywebproject.controller.ShoppingCartController.<init>(ShoppingCartController.java:35)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
... 36 more
Apr 04, 2014 1:30:44 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet appServlet
java.lang.NullPointerException
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getCurrentSession(SQLProductsDataAccess.java:24)
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getInventory(SQLProductsDataAccess.java:35)
at com.nutsaboutcandywebproject.service.ServiceFacadeImpl.getAllProducts(ServiceFacadeImpl.java:140)
at com.nutsaboutcandywebproject.controller.ShoppingCartController.<init>(ShoppingCartController.java:35)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1279)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1192)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
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.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
This is the code for the DAO
package com.nutsaboutcandywebproject.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import com.nutsaboutcandywebproject.model.Category;
import com.nutsaboutcandywebproject.model.Inventory;
import com.nutsaboutcandywebproject.model.Product;
import com.nutsaboutcandywebproject.model.ProductTypes;
public class SQLProductsDataAccess implements IProductsDataAccess {
#Autowired
SessionFactory sessionFactory;
protected Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
public Inventory getInventory()
{
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "from Product";
Query query = session.createQuery(sqlQuery);
System.out.println("Query created...");
#SuppressWarnings("unchecked")
List<Product> productsList = (List<Product>) query.list();
Inventory inventory = new Inventory();
inventory.setProducts(productsList);
transaction.commit();
session.close();
return inventory;
}
public Product getProductById(Integer id) {
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
Query hqlQuery = session.createQuery("from Product WHERE id = :id");
hqlQuery.setParameter("id", id);
System.out.println("Query created...");
List<?> productList = hqlQuery.list();
Product product = (Product) productList.get(0);
transaction.commit();
session.close();
return product;
}
public List<Category> getCategoryName()
{
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "from Category";
Query query = session.createQuery(sqlQuery);
System.out.println("Query created...");
List<Category> categoryList = query.list();
transaction.commit();
session.close();
return categoryList;
}
#Override
public Integer addStock(Integer id)
{
Product product = getProductById(id);
int quantity = product.getQuantityInStock() + 1000;
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "UPDATE Product set quantityInStock = :quantity"
+ " where id = :id";
Query query = session.createQuery(sqlQuery);
query.setParameter("quantity", quantity);
query.setParameter("id", id);
query.executeUpdate();
transaction.commit();
session.close();
return quantity;
}
#Override
public List<ProductTypes> getTypeName() {
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "from ProductTypes";
Query query = session.createQuery(sqlQuery);
System.out.println("Query created...");
List<ProductTypes> typeList = query.list();
transaction.commit();
session.close();
return typeList;
}
#Override
public void updateProduct(Integer updatedQuantity, Integer productId) {
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "UPDATE Product set quantityInStock = :quantity"
+ " where id = :id";
Query query = session.createQuery(sqlQuery);
query.setParameter("quantity", updatedQuantity);
query.setParameter("id", productId);
System.out.println("Query created...");
query.executeUpdate();
transaction.commit();
session.close();
}
#Override
public Integer deleteProduct(Integer productId)
{
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
Query query = session.createQuery("delete Product where id = :id");
query.setParameter("id",productId);
int result = query.executeUpdate();
transaction.commit();
session.close();
return result;
}
}
ShoppingCartController
package com.nutsaboutcandywebproject.controller;
#SessionAttributes(value = {"customerSession","cartSession"})
#Controller
public class ShoppingCartController {
private ServiceFacade facade = new ServiceFacadeImpl();
private NACExceptions exceptionsNAC = new NACExceptions();
private List<Product> productsList = facade.getAllProducts();
private List<Category> categoryList = facade.getCategory();
private List<ProductTypes> typeList = facade.getType();
private List<Sizes> sizeList = facade.getAllSizes();
private List<ProductPriceMatrix> priceMatrixList = facade.getProductPriceMatrices();
private List<String> exceptionList = new ArrayList<String>();
#RequestMapping(value = "/cart", method = RequestMethod.POST)
public String doShop(Model model, #RequestParam("smallSize") String[] small,
#RequestParam("mediumSize") String[] medium ,#RequestParam("largeSize") String[] large)
{
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession();
List<ShoppingCart> cartList = new ArrayList<ShoppingCart>();
boolean isCartEmpty = true;
if(session.getAttribute("cartSession")!=null){
cartList = (List<ShoppingCart>) session.getAttribute("cartSession");
isCartEmpty = false;
}
for(int index=0; index<productsList.size();index++){
int numberOfSmall = 0;
int numberOfMedium = 0;
int numberOfLarge = 0;
Integer productId = productsList.get(index).getId();
Sizes size = priceMatrixList.get(index).getSize();
Product product = facade.getSingleProduct(productId);
try{
exceptionsNAC.numberCheck(small[index]);
exceptionsNAC.numberCheck(medium[index]);
exceptionsNAC.numberCheck(large[index]);
exceptionsNAC.checkValues(small[index]);
exceptionsNAC.checkValues(medium[index]);
exceptionsNAC.checkValues(large[index]);
numberOfSmall = Integer.parseInt(small[index]);
numberOfMedium = Integer.parseInt(medium[index]);
numberOfLarge = Integer.parseInt(large[index]);
}catch(ProductException e){
exceptionList.add(e.getMessage());
}
User user = (User) session.getAttribute(("customerSession"));
if(small[index] != null && numberOfSmall!=0){
try {
if(exceptionsNAC.getRemainingQuantityInStock(50,numberOfSmall,product.getId())){
ShoppingCart cart = new ShoppingCart(0,user,product,size,numberOfSmall);
cartList.add(cart);
}
} catch (ProductException e) {
exceptionList.add(e.getMessage());
}
}
if(medium[index] != null && numberOfMedium!=0){
try {
if(exceptionsNAC.getRemainingQuantityInStock(100,numberOfMedium,product.getId())){
ShoppingCart cart = new ShoppingCart(0,user,product,size,numberOfMedium);
cartList.add(cart);
}
} catch (ProductException e) {
exceptionList.add(e.getMessage());
}
}
if(large[index] != null && numberOfLarge!=0){
try {
if(exceptionsNAC.getRemainingQuantityInStock(150,numberOfLarge,product.getId())){
ShoppingCart cart = new ShoppingCart(0,user,product,size,numberOfLarge);
cartList.add(cart);
}
} catch (ProductException e) {
exceptionList.add(e.getMessage());
}
}
}
if(isCartEmpty){
session.setAttribute("cartSession", cartList);
}
model.addAttribute("cartSession", cartList);
model.addAttribute("productsList", productsList);
model.addAttribute("categoryList", categoryList);
model.addAttribute("typeList", typeList);
model.addAttribute("sizeList", sizeList);
model.addAttribute("priceMatrixList", priceMatrixList);
model.addAttribute("exception", exceptionList);
return "/ShoppingCart";
}
}
You are missing "dao" package in your component-scan config:
<context:component-scan base-package="com.nutsaboutcandywebproject.controller"/>
<context:component-scan base-package="com.nutsaboutcandywebproject.dao"/>
Also, DAO class must have #Repository annotation in order to use it as an autowired component.
Your DAO and service objects need to be beans under Spring control. By instantiating them like this:
private ServiceFacade facade = new ServiceFacadeImpl();
Spring never gets to inject your dependencies and wire everything up, hence the NPE. Add the following to your XML file
<context:component-scan base-package="com.nutsaboutcandywebproject.dao"/>
<context:component-scan base-package="com.nutsaboutcandywebproject.service"/>
and make sure your DAO is marked with #Repository or #Component, and your services as #Service or #Component. And change the instantiation of facade to
#Autowired
private ServiceFacade facade;
Since there was no scan for the DAO package, you almost certainly have to do the same in ServiceFacadeImpl and its IProductsDataAccess field.
Update: Besides this, you're accessing beans which haven't been initialised yet, e.g.
private List<Product> productsList = facade.getAllProducts();
At that point in time, i.e. during object instantiation, Spring hasn't finished creating your DAOs, Hibernate session factory, etc. You can only access these beans and set your fields when Spring has finished initialising and injecting the dependencies. To do that, put the code in an initialisation method marked with #PostConstruct:
#Controller
public class ShoppingCartController {
#Autowired
private ServiceFacade facade;;
private NACExceptions exceptionsNAC = new NACExceptions();
private List<Product> productsList;
private List<Category> categoryList;
private List<ProductTypes> typeList;
private List<Sizes> sizeList;
private List<ProductPriceMatrix> priceMatrixList;
private List<String> exceptionList = new ArrayList<String>();
#PostConstruct
public void someInitializationMethod() {
productsList = facade.getAllProducts();
categoryList = facade.getCategory();
typeList = facade.getType();
sizeList = facade.getAllSizes();
priceMatrixList = facade.getProductPriceMatrices();
}
....
Add few more lines like this - in order to initiate the bean along with the datasource
<bean id="shoppingCartController" class="point.it.to.implementation.class">
<property name="mySessionFactory" ref="mySessionFactory"/>
</bean>
You can even try using #Autowired annotation, by simplying creating the setter method for it.

Categories

Resources