Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp
I'm trying to combine Hibernate, MySQL 5.0 and Eclipse plugin to build a basic medical records app.
I'm making slow progress but the latest problem is that I have to deal with is that I cannot open a connection. When I run the app as a simple java app rather than a plug-in, the db accesses just fine. When I run as a plugin, I get the exception noted below in the Full Stack Trace section.
I'm stumped. Any help would be appreciated!
Roy
Output from my program is :
Patient.getPatient called.
HibernateUtil called
HibernateUtil configuration completed. Properties= jdbc:mysql://localhost:3306/medrec
HibernateUtil.getSession>threadsession= java.lang.ThreadLocal@d98810
My HibernateUtil class:
Code:
/*
* Created on Feb 16, 2006
*/
package yetanothertry.medrecmodel;
import java.io.File;
import java.net.URL;
import java.util.Properties;
import org.apache.log4j.*;
import org.eclipse.core.runtime.*;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.osgi.framework.Bundle;
/**
* @author RAD
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
private static final ThreadLocal threadSession = new ThreadLocal();
private static final ThreadLocal threadTransaction = new ThreadLocal();
private static final Configuration cfg = new Configuration();
private static Logger log = Logger.getLogger(HibernateUtil.class);
static {
try {
System.out.println("HibernateUtil called");
Bundle bundle = Platform.getBundle("YetAnotherTry");
sessionFactory = cfg.configure().buildSessionFactory();
System.out.println("HibernateUtil configuration completed. Properties= "+cfg.getProperty("hibernate.connection.url"));
}
catch(Throwable ex) {
System.out.println("HibernateUtil failed. "+ex);
ex.printStackTrace();
//if (ex instanceof ExceptionInInitializerError)
throw new ExceptionInInitializerError(ex);
}
}
public HibernateUtil() {
BasicConfigurator.configure();
}
public static Session getSession() {
Session sess = (Session)threadSession.get();
try {
if (sess==null) {
sess = sessionFactory.openSession();
threadSession.set(sess);
log.debug("HibernateUtil.getSession>new session");
}
}catch (HibernateException ex) {
System.out.println("HibernateUtil.getSessionFactory failed" +ex);
throw new ExceptionInInitializerError(ex);
}
System.out.println("HibernateUtil.getSession>threadsession= "+threadSession);
return sess;
}
public static void closeSession() {
try {
Session sess= (Session)threadSession.get();
threadSession.set(null);
if (sess != null && sess.isOpen())
sess.close();
}catch (HibernateException ex) {
System.out.println("HibernateUtil.close failed" +ex);
throw new ExceptionInInitializerError(ex);
}
System.out.println("HibernatUtil.closeSession>threadSession= "+threadSession);
}
public static void beginTransaction() {
Transaction tx = (Transaction)threadTransaction.get();
log.debug("HibernateUtil.beginTransaction>new session = "+tx);
try {
if (tx == null) {
tx = getSession().beginTransaction();
threadTransaction.set(tx);
}
}catch (HibernateException ex) {
System.out.println("HibernateUtil.beginTransaction failed" +ex);
throw new ExceptionInInitializerError(ex);
}
}
public static void commitTransaction() {
Transaction tx = (Transaction)threadTransaction.get();
System.out.println("HibernateUtil.commitTransaction. tx= "+tx.wasCommitted()+". "+tx.wasRolledBack());
try {
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) tx.commit();
threadTransaction.set(null);
}catch (HibernateException ex) {
rollbackTransaction();
System.out.println("HibernateUtil.commitTransaction failed. "+ex);
throw new ExceptionInInitializerError(ex);
}
}
public static void rollbackTransaction() {
Transaction tx = (Transaction)threadTransaction.get();
try {
threadTransaction.set(null);
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) tx.rollback();
}catch (HibernateException ex) {
System.out.println("HibernateUtil.commitTransaction failed" +ex);
throw new ExceptionInInitializerError(ex);
}finally {
closeSession();
}
}
}
Hibernate version: 3.1 Mapping documents:<?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="connection.driver_class" >
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/medrec
</property>
<property name="connection.username">
mm
</property>
<property name="connection.password"></property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="yetanothertry/medrecmodel/Patient.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Patient.hbm.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate-mapping" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="yetanothertry.medrecmodel.Patient" table="patient">
<id name="id" column="patient_id">
<generator class="native"/>
</id>
<property name="lastName" column="lastname" />
<property name="firstName" column="firstname" />
<property name="birthdate" column="birthdate" type="java.sql.Date"/>
<property name="gender" column="gender" />
</class>
</hibernate-mapping>
Code between sessionFactory.openSession() and session.close():Code:
Patient.java file:
/*
* Created on Oct 5, 2005
*/
package yetanothertry.medrecmodel;
import java.text.*;
import java.util.*;
import org.apache.log4j.Logger;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.ui.views.properties.IPropertySource;
import org.hibernate.Session;
/**
* @author RAD
*/
public class Patient {
private String lastName = null;
private String firstName = null;
private Long id;
private java.sql.Date birthdate = null;
private String gender = null;
static Logger log = Logger.getLogger(Patient.class);
public Patient() {}
public Patient(String name) {
List list = HibernateUtil.getSession().createQuery("from Patient where name= '"+name+"'").list();
log.info(list.toString());
}
public Patient(String last,String first,String gender, String bday) {
this.lastName = last;
this.firstName = first;
this.gender = gender;
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
try {
birthdate = new java.sql.Date(df.parse(bday).getTime());
System.out.println("Patient.dateFormat. birthdate= "+birthdate+". bday= "+bday);
}catch(ParseException pe) {System.out.println("Patient.init> "+pe);}
}
public void setLastName(String last) { this.lastName=last;}
public String getLastName() { return lastName;}
public String getFirstName() { return firstName;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public Long getId() { return id;}
private void setId(Long id) { this.id = id;}
public java.sql.Date getBirthdate() {return birthdate;}
public void setBirthdate(java.sql.Date birthday) {this.birthdate = birthday;}
public String getGender() {return gender;}
public void setGender(String gender) {this.gender = gender;}
[color=darkred]public static List getPatients() {
System.out.println("Patient.getPatients called");
Session session = HibernateUtil.getSession();
session.beginTransaction();
List list = session.createQuery("from Patient").list();
session.getTransaction().commit();
log.info(list.toString());
return list;
} [/color]
public static Patient getPatient(String firstName, String lastName) {
System.out.println("Patient.getPatient called.");
Patient pat = null;
List allPatients = getPatients();
System.out.println("Patient.getPatient allPatients = "+allPatients);
Iterator ptIter = allPatients.iterator();
System.out.println("Patient.getPatient iterator. pat= "+ptIter);
search:
while (ptIter.hasNext()) {
pat = (Patient)ptIter.next();
System.out.println("Patient.getPatient iterator. pat= "+pat);
//search by last name first and make a list of all matches
if (firstName!=null) {
if (firstName.equals(pat.getFirstName())) {
break search;
}
}
}
return pat; }
public boolean equals(Object obj) {
if (obj==this) return true;
if (!(obj instanceof Patient)) return false;
Patient pat = (Patient)obj;
if (!(pat.getFirstName().equals(getFirstName()))) return false;
if (!(pat.getLastName().equals(getLastName()))) return false;
if (!(pat.getBirthdate().equals(getBirthdate()))) return false;
return true;
}
public String toString() { return lastName+" , "+ firstName+". ID= "+getId();}
}
Full stack trace of any exception that occurs:!MESSAGE Cannot open connection
!STACK 0
org.hibernate.exception.JDBCConnectionException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:420)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
at yetanothertry.medrecmodel.Patient.getPatients(Patient.java:59)
at yetanothertry.medrecmodel.Patient.getPatient(Patient.java:71)
at yetanothertry.views.PatientView$2.run(PatientView.java:123)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:499)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:539)
at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:488)
at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:400)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:66)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:928)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3348)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2968)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1914)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1878)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:419)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:95)
at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:78)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:92)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:68)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:400)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:177)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.core.launcher.Main.invokeFramework(Main.java:336)
at org.eclipse.core.launcher.Main.basicRun(Main.java:280)
at org.eclipse.core.launcher.Main.run(Main.java:977)
at org.eclipse.core.launcher.Main.main(Main.java:952)
Caused by: java.sql.SQLException: No suitable driver
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
... 33 more
Name and version of the database you are using: MySQL Server 5.0The generated SQL (show_sql=true): None. It never gets that far. Debug level Hibernate log excerpt: None ever displays, except as above. Problems with Session and transaction handling?
Read this:
http://hibernate.org/42.htmlCode:
Code: