我正在尝试配置hibernate和tomcat,以便tomcat将管理数据库连接,但是我遇到了一些错误。
你能帮忙吗?这是我的代码:
这是HibernateUtil
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) {
// 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() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
HibernateListener:
public class HibernateListener implements ServletContextListener {
/* public void contextInitialized(ServletContextEvent event) {
HibernateUtil.getSessionFactory(); // Just call the static initializer
// of that class
}
public void contextDestroyed(ServletContextEvent event) {
HibernateUtil.getSessionFactory().close(); // Free all resources
}
}*/
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("\n\tInside contextInitialized()\n")
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
HibernateUtil.shutdown();
}
}
我还在web.xml中创建了一个条目
<listener>
<listener-class>hibernate.HibernateListener</listener-class>
</listener>
我创建了一个jsp文件并尝试运行一段代码,即:
public Employee getEmployeeByLogin(String login){
Employee p= null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Query query = session.createQuery("from employee p where p.login = '" + login +"'");
p = (Employee) query.uniqueResult();
return p;
}
我得到的错误是:
org.apache.jasper.JasperException: org.hibernate.HibernateException: createQuery is not valid without active transaction
我尝试按https://community.jboss.org/wiki/UsingHibernateWithTomcat#中描述的方式进行,但没有成功...... 再一次。请帮忙。