Я изучаю работу Java CRUD с Hibernate. Я использую базу данных MYSQL для серверной части и она работает без проблем. Но когда я запускаю приложение, оно показывает следующие ошибки.
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)
Вот код 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());
}
}
Вот код в 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();
}
}
Вот код в классе пользователя.
@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;
}
}
Вот код 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();
}
}
Вот файл 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.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>
Вот код в файле hibernate.revenge.xml ..
<?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>
Вот код HTML.
<!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>
Вот снимок экрана, когда я запускаю приложение.