if it helps this is the code
package com.myp.db;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
import org.apache.log4j.Logger;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
public class Connect
{
static Logger logger = Logger.getLogger(Connect.class);
private static ArrayList instances = new ArrayList();
private String filename = null;
private SessionFactory sessionFactory = null;
private Session session = null;
private Configuration cfg = null;
private Transaction tx = null;
/**
* Return the name of properties file for this class
*
* @param c1 class
* @return file name
*/
static private String getPropFile(Class c1)
{
if (!c1.getName().startsWith("com.umusic.ecrm.db.")) {
System.err.println("Class " + c1.getName() + " is not in com.umusic.ecrm.db package!");
throw new RuntimeException();
}
return c1.getPackage().toString().replace( "package com.umusic.ecrm.db.", "") + ".h.properties";
}
/**
* Read hibernate.properties from file
*
* @return Properties from the <code>hibernate.properties</code> file.
*/
private Properties getProps(String propFileName)
{
Properties props = new Properties();
try {
InputStream instr = this.getClass().getResourceAsStream( propFileName );
if (instr == null) {
System.err.println("Hibernate properties file " + propFileName + " not found");
throw new RuntimeException();
}
props.load(instr);
} catch (java.io.IOException e) {
System.err.println("Hibernate properties file " + propFileName + " is unreadable");
throw new RuntimeException();
}
return props;
}
/**
* Constructor with hibernate.properties file
*/
private Connect(String hPropFileName)
{
cfg = new Configuration().setProperties(getProps(hPropFileName));
}
private void setFilename(String name)
{
filename = name;
}
/**
* Return name of the properties file used to initialized this class.
*
* @return name of the <code>hibernate.properties</code> file.
*/
private String getFilename()
{
return filename;
}
/**
* Return an instance configured according to the properties file
*
* @return Instance of the <code>Connect</code> singleton.
*/
private static synchronized Connect getInstance(String hPropFileName)
{
if (hPropFileName == null || hPropFileName.length() < 1) {
System.err.println("Empty properties file name!");
throw new RuntimeException();
}
Iterator it = instances.iterator();
while (it.hasNext()) {
Connect c = (Connect) it.next();
if (c.getFilename().equals(hPropFileName)) {
logger.warn("returning existing instance of " + hPropFileName);
return c;
}
}
// create new instance and add it to the list
Connect inst = new Connect(hPropFileName);
logger.warn("creating new instance of " + hPropFileName);
inst.setFilename(hPropFileName);
instances.add(inst);
return (Connect) instances.get(instances.size() - 1);
}
/**
* Figure out the name of the properties file and load it
*
* @param c1 class to load the properties for
* @return instance of the Connect class
*/
public static synchronized Connect getInstance(Class c1)
{
Connect c = getInstance(getPropFile(c1));
c.addClass(c1);
return c;
}
/**
* Configure according to the properties file and add classes
*
* @return Instance of the <code>Connect</code> singleton.
*/
public static synchronized Connect getInstance(Class c1, Class c2)
{
Connect c = getInstance(getPropFile(c1));
c.addClass(c1);
c.addClass(c2);
return c;
}
/**
* Configure according to the properties file and add classes
*
* @return Instance of the <code>Connect</code> singleton.
*/
public static synchronized Connect getInstance(Class c1, Class c2, Class c3)
{
Connect c = getInstance(getPropFile(c1));
c.addClass(c1);
c.addClass(c2);
c.addClass(c3);
return c;
}
/**
* Configure according to the properties file and add classes
*
* @return Instance of the <code>Connect</code> singleton.
*/
public static synchronized Connect getInstance(String hFile, Class c1, Class c2, Class c3, Class c4)
{
Connect c = getInstance(hFile);
c.addClass(c1);
c.addClass(c2);
c.addClass(c3);
c.addClass(c4);
return c;
}
/**
* Add class
*/
public void addClass(Class cl)
{
if( getFilename() != null && !getPropFile(cl).equals( getFilename() ) )
{
System.err.println( cl.getName() + " does not belong to package " + getFilename() );
throw new RuntimeException();
}
try {
if( cfg.getClassMapping( cl ) == null ) cfg.addClass( cl );
} catch (MappingException e) {
System.err.println("Mapping Exception" + e.getMessage());
throw new RuntimeException(e);
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
}
/**
* @return non-transactional <code>Session</code> retrieved from Hibernate <Code>SessionFactory</code>
*/
public Session getSession()
{
return getSession(false);
}
/**
* @return <code>Session</code> retrieved from Hibernate <Code>SessionFactory</code>
*/
public Session getSession(boolean transaction)
{
try {
if (sessionFactory == null) sessionFactory = cfg.buildSessionFactory();
/*
* Use the Hibernate Session Factory to return an open session to the caller.
*/
session = sessionFactory.openSession();
if (transaction) tx = session.beginTransaction();
return session;
} catch (HibernateException e) {
/*
* Upon encountering a Hibernate generated Exception, we are throwing
* an unchecked RuntimeExcpetion that will cause the user's request to fail.
*
*/
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
}
/**
* close an open session
*/
public void closeSession()
{
if (session != null) {
try {
session.close();
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
}
}
/**
* Commit and close session
*/
public void commit()
{
if (session == null) {
System.err.println("Runtime Exception on commit: no valid session, use getSession( true )");
throw new RuntimeException();
}
if (tx == null) {
System.err.println("Runtime Exception on commit: no valid transaction, use getSession( true )");
throw new RuntimeException();
}
try {
try {
tx.commit();
} catch (HibernateException he) {
System.err.println("Hibernate Exception on commit: " + he.getMessage() + "; rolling back");
if (tx != null) tx.rollback();
throw he;
}
} catch (HibernateException e) {
System.err.println("Hibernate Exception on rollback: " + e.getMessage());
throw new RuntimeException(e);
}
finally {
closeSession();
}
}
/**
* get() returns an object from database with given id. If not found, returns null.
* example: Country c = (Country) get( Country, 20 );
*
* @param id The <code>Long</code> id of desired <code>Class</code>
* @return <code>Class</code> with given id, if it exists. Otherwise, returns null.
*/
public Object get(Class cl, Long id)
{
if (getSession() == null) return null;
try {
return session.load(cl, id);
}
/*
* If the object is not found, i.e., no Country exists with the
* requested id, we want the method to return null rather
* than throwing an Exception.
*
*/ catch (ObjectNotFoundException onfe) {
return null;
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
finally {
closeSession();
}
}
/**
* insert() inserts new <code>Object</code> into the database through Hibernate.
* example: Country c; ... insert( c );
*
* @param obj A new <code>Object</code> to be added.
*/
public void insert(Object obj)
{
if (getSession() == null) return;
try {
session.save(obj);
session.flush(); // commit
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
finally {
closeSession();
}
}
/**
* delete() inserts new <code>Object</code> into the database through Hibernate.
* example: Country c; ... insert( c );
*
* @param obj A new <code>Object</code> to be added.
*/
public void delete(String query)
{
if (getSession(true) == null) return;
try {
session.delete(query);
session.flush(); // commit
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
finally {
commit();
closeSession();
}
}
/**
* update() updates specfied object through Hibernate.
* example: Country c; ... update( c );
*
* @param obj An <code>Object</code> to be updated
*/
public void update(Object obj)
{
if (getSession() == null) return;
try {
session.update(obj);
session.flush(); // ensure the object is saved
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
finally {
closeSession();
}
}
/**
* getList() returns list of all <code>objects</code> objects stored in the database.
* example: Country c = (Country) getList( "from Country" ).get(0);
*
* @return <code>List</code> of objects.
*/
public List getList(String query)
{
if (getSession() == null) return null;
try {
Query qry = session.createQuery(query);
return qry.list();
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
finally {
closeSession();
}
}
/**
* getQuery() returns list of all <code>objects</code> objects stored in the database.
* NOTE: leaves session open. Must be ended with getList( Query )!
* example: Query q = con.getQuery( "from Country where countryId=:cid" );
* q.setString( "cid", "US" );
* List lst = con.getList( q );
*
* @return <code>Query</code> object.
*/
public Query getQuery(String query)
{
if (getSession() == null) return null;
try {
return session.createQuery(query);
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
}
/**
* getList() returns list of all <code>objects</code> objects stored in the database.
* example: Country c = (Country) getList( "from Country" ).get(0);
*
* @return <code>List</code> of objects.
*/
public List getList(Query query)
{
try {
return query.list();
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
finally {
closeSession();
}
}
/**
* getCount() returns integer count of objects based on the query
* example: int c = getCount( "select count(*) from Country" );
*
* @return <code>count</code> of objects.
*/
public int getCount(String query)
{
if (getSession() == null) return 0;
try {
return ((Integer) session.iterate(query).next()).intValue();
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
finally {
closeSession();
}
}
}
|