Jump to content United States-English
HP.com Home Products and Services Support and Drivers Solutions How to Buy
» Contact HP
More options
HP.com home
HP Open Source Middleware Stacks Blueprint:: Web Server on HP ProLiant and HP Integrity Servers with Red Hat Enterprise Linux Version 5

Appendix D: Hibernate Test Application Source Code

» 

Technical documentation

Complete book in PDF
» Feedback
Content starts here

 » Table of Contents

This appendix provides the contents of the following two Hibernate Test Application source code files:

  • HibernateSessionFactory.java

  • hibernate.jsp

The following are the contents of the HibernateSessionFactory.java file:

package com.hp.osms.hibernate.utility;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static Configuration configuration = new Configuration();
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

    private HibernateSessionFactory() {
    }
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
  	if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
		session = (sessionFactory != null) ? sessionFactory.openSession():null;
			threadLocal.set(session);
		}
        return session;
    }
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
		System.err.println("Can not create SessionFactory!!");
			e.printStackTrace();
		}
	}
	public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);
        if (session != null) 
            session.close();
    }
public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}
}

The following are the contents of the hibernate.jsp file:

<%@ page language="java" import="java.util.*,
org.hibernate.HibernateException, org.hibernate.Query,org.hibernate.Transaction,
	com.hp.osms.hibernate.utility.HibernateSessionFactory,
	com.hp.osms.hibernate.Users" pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head><title>Simple Hibernate test Page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
  <%!
  public void showData(JspWriter out,List list)
  {
    Iterator it = list.iterator();
    try{
out.print("<table width='100%' border='1' cellspacing='0' cellpadding='0'><tr>");
	out.print("<tr><td bgcolor='E2E6F1'><div align='center'>UserID<br></div></td>");
	out.print("<td bgcolor='E2E6F1'><div align='center'>FirstName<br></div></td>");
	out.print("<td bgcolor='E2E6F1'><div align='center'>LastName<br></div></td></tr>");
	while(it.hasNext())
	{ Users users = (Users)it.next();
	 out.print("<tr><td><div + align='center'>"+users.getUserId()
 + "<br></div></td>");
	out.print("<td><div align='center'>"+users.getFirstName()
 + "<br></div></td>");
	out.print("<td><div align='center'>"+users.getLastName()
 + "<br></div></td></tr>");
	}
	 out.print("</tr></table>");				 
	}catch(Exception e){e.printStackTrace();} 
  }
  %>
   <%!
  	org.hibernate.Session hbsession = null;
  	void initSession()
  	{ hbsession = HibernateSessionFactory.getSession();}
  	public List queryAll()//query table users from database
  	{
  	  List list = null;
	  try{
		String hsql = "from Users";
		org.hibernate.Query query = hbsession.createQuery(hsql);
		list = query.list();
		return list;
		}catch(HibernateException he)
              {	he.printStackTrace();
			return list; }
       }
public Long insert()
{
  try{   Transaction tx = hbsession.beginTransaction();
	   Users users= new Users();
	   users.setFirstName("Smith");
	   users.setLastName("Barney");
   	           
	   hbsession.save(users);
	   hbsession.flush();
	   tx.commit();
	  return users.getUserId();
	 }catch(HibernateException he){ he.printStackTrace();
		return null;} 
}
	public void update(Long userID)
	{
	   try{	Transaction tx = hbsession.beginTransaction();
			Users users = (Users)hbsession.get(Users.class,userID);
			users.setLastName("root");
			
			hbsession.save(users);
            	hbsession.flush();
    			tx.commit();
    		}catch(HibernateException he){ he.printStackTrace();}
	}
  	public void delete(Long userID)
  	{
  	   try{Transaction tx = hbsession.beginTransaction();
	   	String hsql = "delete Users where user_id="+userID;
	   	Query query = hbsession.createQuery(hsql);
	   	query.executeUpdate();
	   	tx.commit();
		}catch(HibernateException he){ he.printStackTrace();}
	}
	public void clean()
	{ HibernateSessionFactory.closeSession(); }
   %>
  <body><div align="center"><font size="7">OSMS Hibernate Test Page</font>
  <%initSession();%> 
  </div><h2>1.Retrieve data from table USERS via hibernate<br>
   <%showData(out,queryAll());%>
  <h2>2.Insert firstname 'Smith',lastname 'Barney' into table USERS 
and show the query result via hibernate<br>
   <%Long userId=insert();%>
   <%showData(out,queryAll());%>
  <h2>3.Update lastname of the record which inserted in step 2 to 'root' 
and retrieve it via hibernate<br> 
   <%update(userId);%>
    <%showData(out,queryAll());%>
   <h2>4.Delete the test data then query again via hibernate<br> 
   <%delete(userId);%>
   <%showData(out,queryAll());%>
   <%clean();%>
  </body>
</html>
Printable version
Privacy statement Using this site means you accept its terms Feedback to webmaster
© 2007 Hewlett-Packard Development Company, L.P.