Persisting an Object
A custom function has been created to persist a single object using Hibernate. The arguments are the Class name and the object to be persisted. The function at present takes a single object, however you can tweak to persist a collection of objects. My project demanded me to mostly persist a single object, so I have designed it this way. While persisting an object SaveOrUpdate method is used. Therefore if an entry already exists it overwrites it else creates a new entry.
Retrieving an Collection of Object
Another function getObjects is used to get the collection of objects in a List (java.util.List). The arguments are the class name and the query. In both the functions a new SessionFactory has been created to avoid runtime errors.
Simple Interface for Hibernate Operations in Java
package conFIGURATION;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Hibernate {
public int persist(String className,Object obj){
try{
Configuration config = new Configuration();
config.addClass(Class.forName(className));
config.configure();
SessionFactory factory = config.buildSessionFactory();
Session new_session = factory.openSession();
new_session.beginTransaction();
new_session.saveOrUpdate(obj);
new_session.getTransaction().commit();
new_session.close();
}
catch(Exception ex){
System.out.println("Error in Persisting");
System.out.println(ex.getMessage());
ex.printStackTrace();
}
return 1;
}
public List getObjects(String className,String query){
List list = null;
try{
Configuration config = new Configuration();
config.addClass(Class.forName(className));
config.configure();
SessionFactory factory = config.buildSessionFactory();
Session new_session = factory.openSession();
new_session.beginTransaction();
list = new_session.createQuery(query).list();
new_session.getTransaction().commit();
new_session.close();
}
catch(Exception ex){
System.out.println("Error in retrieving");
System.out.println(ex.getMessage());
ex.printStackTrace();
}
return list;
}
}