Eclipse Spring Bean creation error - java

I am trying to run a sample code for simple form registration using spring hibernate and jsp. However, when I try to run the code in eclipse I get the following error. Thanks for the help!
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'con' defined in class path resource [config/spring-hibernate.xml]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:997)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:943)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at com.student.dao.StudentDaoImpl.addStudent(StudentDaoImpl.java:27)
at com.student.controller.RegisterServlet.doPost(RegisterServlet.java:57)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.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:956)
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:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ExceptionInInitializerError
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:147)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:990)
... 31 more
Caused by: org.hibernate.exception.SQLGrammarException: Error calling Driver#connect
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:118)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
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:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
at com.student.bean.DBOperation.<clinit>(DBOperation.java:12)
... 38 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'spring'
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 com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:910)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3923)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1273)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2031)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:718)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
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 com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
DBOperation.java
package com.student.bean;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class DBOperation {
private static SessionFactory factory;
private Session session;
static{
factory=new Configuration().configure("config/hibernate.cfg.xml").buildSessionFactory();
}
public Session getConnection(){
if(session==null || !session.isOpen()){
session=factory.openSession();
}
return session;
}
}
Student.java
package com.student.bean;
import java.io.Serializable;
public class Student implements Serializable {
private int rollNo;
private String name;
private String address;
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
RegisterServlet.java
package com.student.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher ;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.student.bean.Student;
import com.student.dao.StudentDaoImpl;
/**
* Servlet implementation class RegisterServlet
*/
public class RegisterServlet extends HttpServlet {
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String page = request.getParameter("page");
RequestDispatcher rd = null;
if (page != null && page.equals("update")) {
String id = request.getParameter("roll");
int roll = 0;
if (id != null)
roll = Integer.parseInt(id);
String name = request.getParameter("name");
String address = request.getParameter("address");
Student student = new Student();
student.setRollNo(roll);
student.setName(name);
student.setAddress(address);
boolean flag = new StudentDaoImpl().updateStudent(student);
if (flag == true)
rd = request.getRequestDispatcher("update.jsp?status=sucess");
else
rd = request.getRequestDispatcher("update.jsp?status=fail");
} else {
String id = request.getParameter("roll");
int roll = 0;
if (id != null)
roll = Integer.parseInt(id);
String name = request.getParameter("name");
String address = request.getParameter("address");
Student student = new Student();
student.setRollNo(roll);
student.setName(name);
student.setAddress(address);
boolean flag = new StudentDaoImpl().addStudent(student);
if (flag == true)
rd = request.getRequestDispatcher("register.jsp?status=sucess");
else
rd = request.getRequestDispatcher("register.jsp?status=fail");
}
if (rd != null)
rd.forward(request, response);
}
}
StudentDao.java
package com.student.dao;
import com.student.bean.Student;
public interface StudentDao {
boolean addStudent(Student student);
boolean updateStudent(Student student);
Student viewStudent(int roll);
boolean deleteStudent(int roll);
}
StudentDaoImpl.java
package com.student.dao;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.student.bean.DBOperation;
import com.student.bean.Student;
public class StudentDaoImpl implements StudentDao {
private static Resource resource;
private static BeanFactory factory;
private Session session;
private Transaction transaction;
static{
resource=new ClassPathResource("config/spring-hibernate.xml");
factory=new XmlBeanFactory(resource);
}
public boolean addStudent(Student student) {
if(session==null || !session.isOpen())
session=((DBOperation)factory.getBean("con")).getConnection();
if(session!=null && session.isOpen()){
transaction=session.beginTransaction();
int id=(Integer)session.save(student);
if(id>0){
transaction.commit();
session.close();
return true;
}
}
return false;
}
public boolean updateStudent(Student student) {
if(session==null || !session.isOpen())
session=((DBOperation)factory.getBean("con")).getConnection();
if(session!=null && session.isOpen()){
transaction=session.beginTransaction();
Query query=session.createQuery("update Student set name=?,address=? where id=?");
query.setParameter(0, student.getName());
query.setParameter(1, student.getAddress());
query.setParameter(2, student.getRollNo());
int count=query.executeUpdate();
if(count>0){
System.out.println("student updated");
transaction.commit();
session.close();
return true;
}
}
return false;
}
public Student viewStudent(int roll) {
System.out.println("finding student :"+roll);
if(session==null || !session.isOpen())
session=((DBOperation)factory.getBean("con")).getConnection();
if(session!=null && session.isOpen()){
Student student=(Student)session.get(Student.class, roll);
if(student!=null){
System.out.println("student found");
return student;
}
}
return null;
}
public boolean deleteStudent(int roll) {
if(session==null || !session.isOpen())
session=((DBOperation)factory.getBean("con")).getConnection();
if(session!=null && session.isOpen()){
transaction=session.beginTransaction();
Query query=session.createQuery("delete from Student where id=?");
query.setParameter(0, roll);
int count=query.executeUpdate();
if(count>0){
System.out.println("student deleted");
transaction.commit();
session.close();
return true;
}
}
return false;
}
}
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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="mapping/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
student.hibernate.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="std" class="com.student.bean.Student">
<property name="rollNo" value=""></property>
<property name="name" value=""></property>
<property name="address" value=""></property>
</bean>
<bean id="con" class="com.student.bean.DBOperation">
</bean>
</beans>
register.jsp
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<table>
<tr><td colspan="4"><center>Employee</center></td></tr>
<tr><td>Register</td>
<td>View</td>
<td>Update</td>
<td>Delete</td>
</tr>
<tr><td colspan="4">
<center><br>
<%if(request.getParameter("status")!=null && request.getParameter("status").equals("sucess")){ %>
<font color="green">Student Registered successfully</font>
<%}else if(request.getParameter("status")!=null && request.getParameter("status").equals("fail")){ %>
<font color="red">Student not Registered </font>
<%} %>
<br>
<form action="Student.register" method="post">
<table>
<tr><td colspan="2"><center>Register Employee</center><br> <hr></td></tr>
<tr><td>Student Roll :</td><td><input type="text" name="roll" required="required"></td></tr>
<tr><td>Student Name :</td><td><input type="text" name="name" required="required"></td></tr>
<tr><td>Student Address :</td><td><input type="text" name="address" required="required"></td></tr>
<tr><td colspan="2"><center><input type="submit" value="Register"></center></td></tr>
</table>
</form>
</center>
</td></tr>
</table>
</center>
</body>
</html>

It is complaining that a 'spring' database doesn't exist in mysql. Perhaps you have to create it before running the sample. It comes from the line:
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring</property>
In your hibernate.cfg.xml file. If you have a database with a different name you can change it there. Perhaps the sample comes with some script that you are meant to run which creates and populates the db.

Related

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [from User]

I'm getting java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [from User] error. I've gone through these question, but didn't helped me.
org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped
Hibernate error - QuerySyntaxException: users is not mapped [from users]
Database table image:
Database Table user.jpg
UserBean.java
package model;
import java.util.ArrayList;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import controller.Login;
import controller.userinfo;
import gfgshfhjdgfhjdhhjfhjd.iModel;
#Entity
#Table(name= "User")
public class UserBean implements iModel
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="Id")
private int id;
#Column(name="Username")
private String username ;
#Column(name="Password")
private String password ;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserBean(){}
public ArrayList<?> getData() {
return userinfo.getUser();
}
}
Userinfo.java
package controller;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import model.UserBean;
import test.HibernateSessionFactory;
public class Userinfo {
public static void saveUser(UserBean user) {
Session session = HibernateSessionFactory.getSessionFactory().openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
public static ArrayList<?> getUser() {
Session session = HibernateSessionFactory.getSessionFactory().openSession();
session.beginTransaction();
List<UserBean> list = (List<UserBean>)session.createQuery("from User").list();
ArrayList<String> list2= new ArrayList<String>();
for(int i=0;i<list.size();i++) {
int tmp = list.get(i).getId();
StringBuilder sBuilder = new StringBuilder();
sBuilder.append(tmp);
list2.add(sBuilder.toString());
list2.add(list.get(i).getUsername());
list2.add(list.get(i).getPassword());
}
if (list != null) {
for (int i = 0; i < list.size(); i++) {
System.out.println("User ID : " + list.get(i).getId());
System.out.println("User First Name : "+ list.get(i).getUsername());
System.out.println("User Last Name : "+ list.get(i).getPassword());
}
}
session.getTransaction().commit();
return list2;
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- SQL Dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Database Connection Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/project</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="show_sql">true</property>
<!-- Specifying Session Context -->
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
<!-- <property name="hibernate.hbm2ddl.auto">create</property> -->
<!-- Mapping With Model Class Containing Annotations -->
<mapping class="model.UserBean" />
</session-factory>
</hibernate-configuration>
Error Log:
May 06, 2018 4:16:04 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [from User]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:133)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:670)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:103)
at controller.Userinfo.getUser(Userinfo.java:28)
at model.UserBean.getData(UserBean.java:55)
at controller.Login.doGet(Login.java:38)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
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:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2430)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2419)
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: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [from User]
at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:217)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:553)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:662)
... 26 more
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:169)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:326)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3706)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3595)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:576)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
... 32 more
Help Please .. Thanks
#Table(name = ...) distinguishes the (resulting SQL) table name, bro!
#Entity(name = ...) distinguishes the "entity name" especially in jpql/hql/criteria queries - defaults to class name. – #xerx593
As I could see from your database scheme, column mapping names in UserBean.java are not correct (e.g. #Column(name="Username") while it should be lowercase). Possibly, the same problem with table name.
Could be a cause
Second possible option is that You didn't indicated to Hibernate what is the result entity. To do so replace createQuery("from User") with createQuery("from UserBean", UserBean.class)

Java Hibernate Web Application failed to Display data with MySQL Database

I am learning Java CRUD operation with Hibernate . I am using MYSQL database for back end and its running without any problem . But when i run the application ,its shows following errors .
java.lang.ExceptionInInitializerError
at com.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:36)
at com.util.HibernateUtil.getSessionFactory(HibernateUtil.java:42)
at com.dao.UserDAO.AllUsers(UserDAO.java:26)
at com.controller.bean.UserBean.getUsers(UserBean.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:498)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:363)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstValue.getValue(AstValue.java:140)
at com.sun.el.parser.AstValue.getValue(AstValue.java:204)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIData.getValue(UIData.java:732)
at org.primefaces.component.datatable.DataTable.getValue(DataTable.java:1002)
at org.primefaces.component.api.UIData.getDataModel(UIData.java:629)
at javax.faces.component.UIData.getRowCount(UIData.java:356)
at org.primefaces.component.api.UIData.calculateFirst(UIData.java:175)
at org.primefaces.component.datatable.DataTableRenderer.preRender(DataTableRenderer.java:110)
at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:82)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:889)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:456)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
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:748)
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [com.mysql.jdbc.Driver]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:245)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.loadDriverIfPossible(DriverManagerConnectionProviderImpl.java:200)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator(DriverManagerConnectionProviderImpl.java:156)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:95)
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 com.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:29)
... 64 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:230)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:242)
Here is code UserBeans ..
ManagedBean(name = "userBean")
#ViewScoped
public class UserBean implements Serializable {
private List<User> usersList;
private List<User> searchList;
private List<User> searchByRecordNoList;
UserDAO userDao = new UserDAO();
User user = new User();
User newuser = new User();
public List<User> getUsers()
{
usersList = userDao.AllUsers();
int count = usersList.size();
return usersList;
}
public void addUser(){
String Remark = newuser.getRemark();
Integer userId=0;
userId= userDao.getId();
newuser.setId(userId);
String Id = Integer.toString(newuser.getId());
newuser.setRecordNo(Integer.toString(userId));
userDao.add(newuser);
System.out.println("User successfully saved.");
FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Save Information","User successfully saved.");
RequestContext.getCurrentInstance().showMessageInDialog(message);
newuser = new User();
}
public void changeUser(User user) {
this.user= user;
}
public void UpdateUser(User user){
String Name = user.getName();
FacesMessage message1= new FacesMessage(FacesMessage.SEVERITY_INFO, "Name",Name);
RequestContext.getCurrentInstance().showMessageInDialog(message1);
userDao.update(user);
System.out.println("User Info successfully saved.");
FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Save Information","User updated successfully .");
RequestContext.getCurrentInstance().showMessageInDialog(message);
user = new User();
}
public void deleteUser(User user){
String Name = user.getName();
//FacesMessage message3= new FacesMessage(FacesMessage.SEVERITY_INFO, "Delete Item",contactName);
// RequestContext.getCurrentInstance().showMessageInDialog(message3);
userDao.delete(user);
FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Delete","Record deleted successfully");
RequestContext.getCurrentInstance().showMessageInDialog(message);
}
public void searchbyRecordno(){
searchByRecordNoList=userDao.SearchByRecordNo(user.getRecordNo());
int count = searchByRecordNoList.size();
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Number of Record Selected:", Integer.toString(count));
RequestContext.getCurrentInstance().showMessageInDialog(message);
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public User getNewuser() {
return newuser;
}
public void setNewuser(User newuser) {
this.newuser = newuser;
}
public List<User> getUsersList() {
return usersList;
}
public void setUsersList(List<User> usersList) {
this.usersList = usersList;
}
public List<User> getSearchList() {
return searchList;
}
public void setSearchList(List<User> searchList) {
this.searchList = searchList;
}
public List<User> getSearchByRecordNoList() {
return searchByRecordNoList;
}
public void setSearchByRecordNoList(List<User> searchByRecordNoList) {
this.searchByRecordNoList = searchByRecordNoList;
}
public void onRowEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage(" Edited Record No", ((User) event.getObject()).getRecordNo());
FacesContext.getCurrentInstance().addMessage(null, msg);
User editeduser = (User) event.getObject();
userDao.update(editeduser);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Edit Cancelled");
FacesContext.getCurrentInstance().addMessage(null, msg);
usersList.remove((User) event.getObject());
}
}
Here is the code in UserDAO..
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.dao;
import java.util.List;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import com.util.HibernateUtil;
import com.model.pojo.User;
public class UserDAO {
private User user;
private User newuser;
private List<User> DaoAllUsers;
private List<User> DaoSearchUserList;
//Session session;
public List<User> AllUsers(){
Session session = HibernateUtil.getSessionFactory().openSession();
try{
session.beginTransaction();
DaoAllUsers = session.createCriteria(User.class).list();
int count =DaoAllUsers.size();
// FacesMessage message1 = new FacesMessage(FacesMessage.SEVERITY_INFO, "List Size", Integer.toString(count));//Debugging Purpose
//RequestContext.getCurrentInstance().showMessageInDialog(message1);
session.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}
session.close();
return DaoAllUsers;
}
public Integer getId (){
Session session = HibernateUtil.getSessionFactory().openSession();
String hql = "select max(U.id) from Users U";
Query query = session.createQuery(hql);
List<Integer> results = query.list();
Integer userId = 1;
if (results.get(0) != null ) {
userId = results.get(0)+1 ;
}
session.flush();
session.close();
return userId;
}
public List<User> SearchByRecordNo(String RecordNo) {
Session session= HibernateUtil.getSessionFactory().openSession();
List<User> daoSearchList = new ArrayList<>();
try{
session.beginTransaction();
Query qu = session.createQuery("From Users U where U.recordNo =:recordNo");//User is the entity not the table
qu.setParameter("recordNo", RecordNo);
daoSearchList=qu.list();
int count = daoSearchList.size();
session.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}
finally {
session.close();
}
return daoSearchList;
}
public void add(User newuser){
Session session = HibernateUtil.getSessionFactory().openSession();
try{
String Id = Integer.toString(newuser.getId());
// begin a transaction
session.beginTransaction();
session.merge(newuser);
session.flush();
System.out.println("NewUser saved, id: " +
newuser.getId());
session.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}
session.close();
}
public void delete(User user){
Session session = HibernateUtil.getSessionFactory().openSession();
try{
String name= user.getName();
session.beginTransaction();
session.delete(user);
session.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}
session.close();
}
public void update(User user){
Session session = HibernateUtil.getSessionFactory().openSession();
try{
session.beginTransaction();
session.update(user);
session.flush();
session.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}
session.close();
}
}
Here is the code in User Class.
#Entity
#Table(name="users"
,catalog="userinformation"
)
public class User implements java.io.Serializable {
private Integer id;
private String recordNo;
private String name;
private Integer age;
private String sex;
private Date dob;
private String remark;
public User() {
}
public User(String recordNo, String name, Integer age, String sex, Date dob, String remark) {
this.recordNo = recordNo;
this.name = name;
this.age = age;
this.sex = sex;
this.dob = dob;
this.remark = remark;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="id", unique=true, nullable=false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name="RecordNo", length=20)
public String getRecordNo() {
return this.recordNo;
}
public void setRecordNo(String recordNo) {
this.recordNo = recordNo;
}
#Column(name="Name", length=50)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="Age")
public Integer getAge() {
return this.age;
}
public void setAge(Integer age) {
this.age = age;
}
#Column(name="Sex", length=20)
public String getSex() {
return this.sex;
}
public void setSex(String sex) {
this.sex = sex;
}
#Temporal(TemporalType.DATE)
#Column(name="Dob", length=10)
public Date getDob() {
return this.dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
#Column(name="Remark", length=50)
public String getRemark() {
return this.remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
//This method writes the values of contact object with System.out.println(Emp.toString()) code
#Override
public String toString() {
return "users"
+ "\n\t RecordNo: " + this.recordNo
+ "\n\t EmployeeName: " + this.name
+ "\n\t Age: " + this.age
+ "\n\t Sex: " + this.sex
+ "\n\t Date of Birth: " + this.dob
+ "\n\t Remark: " + this.remark;
}
}
Here is the code HibernateUtil Class .
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
//Annotation based configuration
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("/hibernate.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 = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
sessionFactory.close();
}
}
Here is the hibernate.cfg.xml file .
<?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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/userinformation?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"/>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.model.pojo.User"/>
<mapping class="com.model.pojo.User"/>
</session-factory>
</hibernate-configuration>
Here is the code in hibernate.revenge.xml file ..
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
<schema-selection match-catalog="userinformation"/>
<table-filter match-name="users"/>
</hibernate-reverse-engineering>
Here is the HTML Code .
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<h2><center>All User Information</center></h2>
</h:head>
<h:body>
<h:form>
<p:commandButton action="Search?faces-redirect=true" icon="ui-icon-search" value="Search" />
</h:form>
<p:spacer> </p:spacer>
<h:form id="form1">
<p:dataTable id="dataTable" var="user" paginator="true" rows="5" value="#{userBean.users}">
<p:column headerText="RecordNo">
<h:outputText value="#{user.recordNo}"/>
</p:column>
<p:column headerText="Name" >
<h:outputText value="#{user.name}"/>
</p:column>
<p:column sortBy="#{user.age}" headerText="Age" >
<h:outputText value="#{user.age}"/>
</p:column>
<p:column headerText="Sex">
<h:outputText value="#{user.sex}"/>
</p:column>
<p:column headerText="Date of Birth" >
<h:outputText value="#{user.dob}">
<f:convertDateTime type="date" pattern="dd-MMM-yyyy"/>
</h:outputText>
</p:column>
<p:column headerText="Remark" >
<h:outputText value="#{user.remark}"/>
</p:column>
</p:dataTable>
</h:form>
<h:panelGroup >
<h3>Add User Information</h3>
<h:form>
<p>User Name: <p:inputText value="#{userBean.newuser.name}" /></p>
<p>User Age: <p:inputText value="#{userBean.newuser.age}" />Enter Number Only</p>
<h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">
<p>Choose Sex:</p>
<p:selectOneMenu label="Sex:" value="#{userBean.newuser.sex}" id="ulist2">
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItem itemLabel="Male" itemValue="Male"/>
<f:selectItem itemLabel="Female" itemValue="Female"/>
</p:selectOneMenu>
</h:panelGrid>
<p>User Date of Birth: <p:calendar id="dop" value="#{userBean.newuser.dob}" label="DatePosted:"
required="true" pattern="dd/MMM/yyyy" effect="slideDown" requiredMessage="Please Enter Date of Posting!"
navigator="true" showButtonPanel="true" yearRange="c-60:c+60" /> </p>
<p>Remark: <p:inputTextarea value="#{userBean.newuser.remark}" /></p>
<p><p:commandButton icon="ui-icon-plusthick" update=":form1:dataTable" type="submit" value="add" action="#{userBean.addUser()}" /></p>
</h:form>
</h:panelGroup>
</h:body>
</html>
Here is the screen shot when i run the application .
Looks like the MySQL driver can't be found. Some things to check:
Has the driver JAR been deployed to the serverlet container or
application server?
Have the connection details been verified through
the container console?

org.hibernate.PropertyNotFoundException: Could not find a getter for a property

i am new to jsf and hibernate
i am just trying to add name in database through jsf and hibernate
i don't know what's wrong with my code
following is my code
newjsf.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>JSF Hibernate CRUD Example</title>
</h:head>
<h:body>
<h:form>
<h:outputText value="Name"/><br/>
<h:inputText value="#{customer.name}"/>
<h:commandButton value="submit" action="#{customer.save()}"/>
</h:form>
</h:body>
</html>
Customer.java
package com.javaknowledge.entity;
import com.javaknowledge.dao.CustomerDao;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class Customer implements java.io.Serializable {
private Integer custID;
private String name;
private String msg;
public Customer() {
}
public Integer getcustID() {
return custID;
}
public void setcustID(Integer custid) {
this.name = custid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void save(){
CustomerDao dao = new CustomerDao();
dao.addCustomer(this);
this.msg = "ok insertation done";
}
}
CustomerDao.java
package com.javaknowledge.dao;
import com.javaknowledge.entity.Customer;
import com.javaknowledge.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class CustomerDao {
public void addCustomer(Customer cust) {
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
session.save(cust);
session.getTransaction().commit();
} catch (RuntimeException e) {
if (trns != null) {
trns.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
}
}
Hibernate mapping
<hibernate-mapping>
<class name="com.javaknowledge.entity.Customer" table="C_name">
<id name="custId" type="java.lang.Integer" column="cust_id">
<generator class="identity"/>
</id>
<property name="name" type="string" column="name"/>
</class>
</hibernate-mapping>
hibernate configuration
<?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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/college</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">1</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping resource="com/javaknowledge/entity/hibernate.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernateutil.java
package com.javaknowledge.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.HibernateException;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
} catch (HibernateException ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void closeSessionFactory() {
sessionFactory.close();
}
}
here is my error log..
An Error Occurred:
java.lang.ExceptionInInitializerError
Stack Trace
javax.faces.el.EvaluationException: java.lang.ExceptionInInitializerError
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:658)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
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:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
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:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
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:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
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:[][1]591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ExceptionInInitializerError
at com.javaknowledge.util.HibernateUtil.<clinit>(HibernateUtil.java:24)
at com.javaknowledge.dao.CustomerDao.addCustomer(CustomerDao.java:18)
at com.javaknowledge.entity.Customer.save(Customer.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at javax.el.ELUtil.invokeMethod(ELUtil.java:332)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:537)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
at com.sun.el.parser.AstValue.invoke(AstValue.java:283)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 36 more
Caused by: org.hibernate.PropertyNotFoundException: Could not find a getter for custId in class com.javaknowledge.entity.Customer
at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:310)
at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:304)
at org.hibernate.tuple.PropertyFactory.getGetter(PropertyFactory.java:497)
at org.hibernate.tuple.PropertyFactory.buildIdentifierAttribute(PropertyFactory.java:87)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:163)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:520)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:148)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:163)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:135)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:400)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1857)
at com.javaknowledge.util.HibernateUtil.<clinit>(HibernateUtil.java:21)
... 49 more
tell me whats wrong ?
Caused by: org.hibernate.PropertyNotFoundException: Could not find a getter for custId in class com.javaknowledge.entity.Customer
It looks as if you have a few typos. In your Customer class, rename custID to custId because your mapping expects a field named custId. Then rename the following methods...
public Integer getcustID() {
return custID;
}
public void setcustID(Integer custid) {
this.name = custid;
}
...to follow the camel-case convention and to use the renamed custId:
public Integer getCustId() {
return custId;
}
public void setCustId(Integer custId) {
this.custId = custId;
}
Also, in setcustID you're setting name instead of setting custId.

java.lang.IllegalArgumentException while added context:component-scan

Here is my spring.xml,along with the maven dependency and package name:
Package name,spring.xml,Maven dependency
i could not provide the spring.xml as code because the namespace converted into link and i cannot post more than 2 link because of reputation.
lower part of spring.xml
<bean id="user" class="com.javacodegeeks.enterprise.rest.jersey.UserDetails"
autowire="byName">
<property name="adminName" value="Root"></property>
<property name="name" value="Sparsh"></property>
</bean>
<bean id="officeAddress" class="com.javacodegeeks.enterprise.rest.jersey.Address">
<property name="roomNumber" value="${roomNumber}"></property>
<property name="streetName" value="office"></property>
</bean>
<bean id="homeAddress" class="com.javacodegeeks.enterprise.rest.jersey.Address">
<property name="roomNumber" value="1"></property>
<property name="streetName" value="home"></property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>
message
</value>
</list>
</property>
</bean>
<bean
class="com.javacodegeeks.enterprise.rest.jersey.DisplayBeanPostProcessor" />
<bean class="com.javacodegeeks.enterprise.rest.jersey.DisplayBeanFactory" />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="variable.properties" />
</bean>
<context:component-scan base-package="com.javacodegeeks.enterprise.rest.jersey" />
Everything was great but when i add
<context:component-scan base-package="com.javacodegeeks.enterprise.rest.jersey" />
facing error as :
java.lang.IllegalArgumentException
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:52)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)
at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298)
at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300)
at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.javacodegeeks.enterprise.rest.jersey.HelloWorldREST.<clinit>(HelloWorldREST.java:122)
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 com.sun.jersey.server.spi.component.ResourceComponentConstructor._construct(ResourceComponentConstructor.java:245)
at com.sun.jersey.server.spi.component.ResourceComponentConstructor.construct(ResourceComponentConstructor.java:233)
at com.sun.jersey.server.impl.resource.PerRequestFactory$PerRequest._getInstance(PerRequestFactory.java:182)
at com.sun.jersey.server.impl.resource.PerRequestFactory$AbstractPerRequest.getInstance(PerRequestFactory.java:144)
at com.sun.jersey.server.impl.application.WebApplicationContext.getResource(WebApplicationContext.java:239)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:83)
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:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
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:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
HelloWorldRest.java
package com.javacodegeeks.enterprise.rest.jersey;
import java.util.List;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import net.sf.json.JSONObject;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
#Path("/helloworld")
public class HelloWorldREST {
#GET
#Path("/signin/")
public Response responseMsg(#QueryParam("email") String email,
#QueryParam("pass") String pass) {
Session session = factory.openSession();
org.hibernate.Transaction tx = session.beginTransaction();
Long password = (Long) session.createQuery(
"select count(*) from UserDetails where EmailID = '" + email
+ "'and password = '" + pass + "'").uniqueResult();
System.out.println(password);
tx.commit();
session.close();
if (password > 0)
return Response.status(200).entity("success").build();
else
return null;
}
#GET
#Path("/signup/")
public Response responseMsg(#QueryParam("name") String name,
#DefaultValue("Nothing to say") #QueryParam("email") String email,
#QueryParam("date") String date, #QueryParam("pass") String pass) {
Session session = factory.openSession();
org.hibernate.Transaction tx = session.beginTransaction();
UserDetails user = (UserDetails) context.getBean("user");
user.setEmailID(email);
if (name.length() != 0)
user.setName(name);
user.setDate(date);
user.setPass(pass);
session.save(user);
tx.commit();
session.close();
return Response.status(200).entity("success").build();
}
#GET
#Path("/submit/")
#Produces(MediaType.APPLICATION_JSON)
public JSONObject submitValue(#QueryParam("start") int start,
#QueryParam("limit") int limit, #QueryParam("page") int page) {
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Query qry = session.createQuery("from UserDetails");
qry.setFirstResult(start);
qry.setMaxResults(limit);
List<UserDetails> userObject = (List<UserDetails>) qry.list();
JSONObject jObject = new JSONObject();
jObject.put("result", userObject);
jObject.put("success", true);
Long count = (Long) session.createQuery(
"select count(*) from UserDetails").uniqueResult();
jObject.put("totalcount", count);
tx.commit();
session.close();
return jObject;
}
#GET
#Path("/delete/")
public Response hqlTruncate() {
String hql = String.format("delete from UserDetails");
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery(hql);
query.executeUpdate();
tx.commit();
session.close();
return Response.status(200).entity("success").build();
}
static AbstractApplicationContext context;
static SessionFactory factory = null;
static {
Configuration config = new Configuration();
config.configure();
ServiceRegistryBuilder srBuilder = new ServiceRegistryBuilder();
srBuilder.applySettings(config.getProperties());
ServiceRegistry serviceRegistry = srBuilder.buildServiceRegistry();
factory = config.buildSessionFactory(serviceRegistry);
context = new ClassPathXmlApplicationContext("spring.xml");
System.out.println(context.getMessage("greeting", null,
"default message", null));
context.registerShutdownHook();
}
}

using hibernate3 and struts2

Im trying to implement a struts 2 and hibernate login application following this tutorial:
Link to the tutorial
When I push login bottton I have an exeption :
GRAVE: Servlet.service() for servlet [default] in context with path [/Test] threw exception [L''exécution du filtre (Filter) a lancé une exception] with root cause
java.lang.ClassNotFoundException: org.jboss.logging.BasicLogger
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2918)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1174)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1669)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:192)
at org.aymen.slimi.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:10)
at org.aymen.slimi.util.HibernateUtil.<clinit>(HibernateUtil.java:5)
at org.aymen.slimi.utilisateur.UserAction.<init>(UserAction.java:22)
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 java.lang.Class.newInstance(Unknown Source)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:151)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:182)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:171)
at com.opensymphony.xwork2.factory.DefaultActionFactory.buildAction(DefaultActionFactory.java:22)
at com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:141)
at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:297)
at com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:397)
at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:37)
at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:552)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
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:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
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)
mai 04, 2014 6:26:37 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [default] in context with path [/Test] threw exception [L''exécution du filtre (Filter) a lancé une exception] with root cause
java.lang.NoClassDefFoundError: Could not initialize class org.aymen.slimi.utilisateur.UserService
at org.aymen.slimi.utilisateur.UserAction.<init>(UserAction.java:22)
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 java.lang.Class.newInstance(Unknown Source)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:151)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:182)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:171)
at com.opensymphony.xwork2.factory.DefaultActionFactory.buildAction(DefaultActionFactory.java:22)
at com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:141)
at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:297)
at com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:397)
at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:37)
at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:552)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
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:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The index.jsp:
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sj" uri="/struts-jquery-tags" %>
<%# taglib prefix="sb" uri="/struts-bootstrap-tags" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Struts2 Bootstrap Plugin Showcase - <s:text name="showcase.version"/> - Client Validation</title>
<meta charset="utf-8"/>
<meta name="keywords" content="struts2, twitter, bootstrap, plugin, showcase" />
<meta name="description" content="A Showcase for the Struts2 Bootstrap Plugin" />
<!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<sj:head jqueryui="false"/>
<sb:head includeScripts="true" includeScriptsValidation="true"/>
<style type="text/css">
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<a class="brand" href="#" style="margin-left:-2px" >Welcome to Aymen Slimi Server</a>
<!--/.nav-collapse -->
</div>
</div>
The User.java:
package org.aymen.slimi.utilisateur;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="user")
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1020834391383853442L;
private String userId;
private String password;
private String firtName;
private String lastName;
#Id
#Column(name="user_name")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Column(name="user_password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name="first_name")
public String getFirtName() {
return firtName;
}
public void setFirtName(String firtName) {
this.firtName = firtName;
}
#Column(name="last_name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
The UserService.java:
package org.aymen.slimi.utilisateur;
import java.util.ArrayList;
import java.util.List;
import org.aymen.slimi.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
public class UserService extends HibernateUtil{
public boolean verifyAccess(User user) {
User userDB = this.getUser(user.getUserId());
if (userDB!=null){
if(user.getUserId().equals(userDB.getUserId()) && user.getPassword().equals(userDB.getPassword())) {
return true;
}
}
return false;
}
public User add(User user) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
return user;
}
public User delete(String username) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
User user = (User) session.load(User.class, username);
if(null != user) {
session.delete(user);
}
session.getTransaction().commit();
return user;
}
public User getUser(String username){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
User user = null;
Query query = session
.createQuery("select * from user where username = :username");
query.setString("username", username);
user = (User) query.uniqueResult();
return user;
}
#SuppressWarnings("unchecked")
public List<User> list() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<User> user = null;
try {
user = ((List<User>)session.createQuery("from user").list());
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
if(user != null) {
return user;
}
return new ArrayList<User>();
}
}
The struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation"
value="false" />
<!--constant name="struts.devMode" value="false" /-->
<!--constant name="struts.custom.i18n.resources"
value="resources" /-->
<include file="struts-login.xml"></include>
<!--include file="struts-security.xml"></include-->
<package name="default" namespace="/" extends="struts-default" >
<action name="/*">
<result>/WEB-INF/jsp/index.jsp</result>
</action>
</package>
</struts>
The struts-login.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="login" namespace="/" extends="struts-default" >
<interceptors>
<interceptor name="login" class="org.aymen.slimi.utilisateur.LoginInterceptor"></interceptor>
<interceptor-stack name="loggingStack">
<interceptor-ref name="login" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<action name="login" class="org.aymen.slimi.utilisateur.UserAction" method="verifyLogin">
<result name="success">/WEB-INF/jsp/main.jsp</result>
<result name="input">/WEB-INF/jsp/index.jsp</result>
</action>
</package>
</struts>
The HibernateUtil.java:
package org.aymen.slimi.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
The web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts2 Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
The list of jar:
Add the JBoss Logging jar to your classpath. If you use Maven, it will add this and any other required jars to the classpath
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
The solution was changing the HibernateUtil.java:
import org.hibernate.*;
import org.hibernate.cfg.*;
#SuppressWarnings("deprecation")
public class HibernateUtil {
public static final SessionFactory sessionFactory;
static {
try {
// Création de la SessionFactory à partir de hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
#SuppressWarnings("rawtypes")
public static final ThreadLocal session = new ThreadLocal();
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
And the jar liste is:

Categories

Resources