Andrew Andrew - 16 days ago 4
Java Question

Hibernate java.lang.ExceptionInInitializerError

I've been working through the Hibernate Tutorial provided by Netbeans but whenever I tried running the program I end up with a

java.lang.ExceptionInInitializerError
. Anyone have any ideas about what's wrong?

Stack Trace:

java.lang.ExceptionInInitializerError
at dvdrental.HibernateUtil.<clinit>(HibernateUtil.java:29)
at dvdrental.FilmHelper.<init>(FilmHelper.java:18)
at dvdrental.FilmController.<init>(FilmController.java:34)
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:408)
at java.lang.Class.newInstance(Class.java:438)
at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:186)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:100)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:257)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:117)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:80)
at org.apache.el.parser.AstValue.getValue(AstValue.java:135)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.UIComponentBase.isRendered(UIComponentBase.java:457)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1850)
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.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.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 org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at dvdrental.HibernateUtil.<clinit>(HibernateUtil.java:25)
... 58 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:344)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:242)
... 73 more


HibernateUtil.java

package dvdrental;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
* Hibernate Utility class with a convenient method to get Session Factory
* object.
*
* @author andre_000
*/
public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}


FilmHelper.java

package dvdrental;

import org.hibernate.Session;
import java.util.List;
import org.hibernate.Query;
/**
*
* @author andre_000
*/
public class FilmHelper {
Session session = null;
public FilmHelper() {
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
}

public List getFilmTitles(int startID, int endID) {
List<Film> filmList = null;
try {
org.hibernate.Transaction tx = session.beginTransaction();
Query q = session.createQuery("from Film as film where film.filmId between '"+startID+"' and '"+endID+"'");
filmList = (List<Film>) q.list();
} catch (Exception e) {
e.printStackTrace();
}
return filmList;
}

public List getActorsByID(int filmId) {
List<Actor> actorList = null;
try {
org.hibernate.Transaction tx = session.beginTransaction();
Query q = session.createQuery("from Actor as where actor.actorId in (select filmActor.actor.actorId from FilmActor as filmActor where filmActor.film.filmId='" + filmId + "')");
actorList = (List<Actor>) q.list();
} catch(Exception e) {
e.printStackTrace();
}
return actorList;
}

public Category getCategoryByID(int filmId) {
List<Category> categoryList = null;
try {
org.hibernate.Transaction tx = session.beginTransaction();
Query q = session.createQuery("from Category as category where category.categoryId in (select filmCat.category.categoryId from FilmCategory as filmCat where filmCat.film.filmId='" + filmId + "')");
} catch (Exception e) {
e.printStackTrace();
}

return categoryList.get(0);
}

public Film getFilmByID(int filmId) {
Film film = null;
try {
org.hibernate.Transaction tx = session.beginTransaction();
Query q = session.createQuery("from Film as film where film.filmId=" + filmId);
film = (Film) q.uniqueResult();
} catch(Exception e) {
e.printStackTrace();
}

return film;
}

public String getLangByID(int langId) {
Language language = null;
try {
org.hibernate.Transaction tx = session.beginTransaction();
Query q = session.createQuery("from Language as lang where lang.languageId=" + langId);
language = (Language) q.uniqueResult();
} catch(Exception e) {
e.printStackTrace();
}

return language.getName();
}

}


FilmController.java

package dvdrental;

import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

/**
*
* @author andre_000
*/
@ManagedBean
@SessionScoped
public class FilmController {

/**
* Creates a new instance of FilmController
*/
int startId;
int endId;
DataModel filmTitles;
FilmHelper helper;
private int recordCount = 1000;
private int pageSize = 10;
private Film current;
private int selectedItemIndex;
public FilmController() {
helper = new FilmHelper();
startId = 1;
endId = 10;
}
public FilmController(int startId, int endId) {
helper = new FilmHelper();
this.startId = startId;
this.endId = endId;
}
public Film getSelected() {
if(current == null) {
current = new Film();
selectedItemIndex = -1;
}
return current;
}

public DataModel getFilmTitles() {
if(filmTitles == null) {
filmTitles = new ListDataModel(helper.getFilmTitles(startId, endId));
}
return filmTitles;
}

void recreateModel() {
filmTitles = null;
}

public boolean isHasNextPage() {
if(endId + pageSize <= recordCount)
return true;
return false;
}

public boolean isHasPreviousPage() {
if(startId-pageSize > 0)
return true;
return false;
}

public String next() {
startId = endId+1;
endId += pageSize;
recreateModel();
return "index";
}
public String previous() {
startId -= pageSize;
endId -= pageSize;
recreateModel();
return "index";
}

public int getPageSize() {
return pageSize;
}

public String prepareView() {
current = (Film) getFilmTitles().getRowData();
return "browse";
}
public String prepareList() {
recreateModel();
return "index";
}
public String getLanguage() {
int langID = current.getLanguageByLanguageId().getLanguageId().intValue();
String language = helper.getLangByID(langID);
return language;
}
public String getActors() {
List actors = helper.getActorsByID(current.getFilmId());
StringBuffer totalCast = new StringBuffer();
for (int i = 0; i < actors.size(); i++) {
Actor actor = (Actor) actors.get(i);
totalCast.append(actor.getFirstName());
totalCast.append(" ");
totalCast.append(actor.getLastName());
totalCast.append(" ");
}
return totalCast.toString();
}

public String getCategory() {
Category category = helper.getCategoryByID(current.getFilmId());
return category.getName();
}
}

Answer

Look at:

Caused by: java.lang.ClassNotFoundException: 
    Could not load requested class : com.mysql.jdbc.Driver

It probably means you don't put the MySQL's driver in classpath.

So, download the jar and add it.

Obs: For Glassfish, like the tutorial you following, put the mysql-connector-java-*-bin.jar in the yourdomain/lib directory of your installation.

Comments