domingo, 28 de diciembre de 2008

Hibernate GenericDao

Hola aqui posteare un ejemplo del manejo de los multiconocidos y muy ùtiles GenericDaos de Hibernate. Tambien, mostrare como acomodar dichos Daos con sus Servicios junto con sus implementaciones respectivas de cada uno. Espero les
paresca interesante.


GenericDAO.java

import java.util.Collection;
import java.util.List;
import org.hibernate.Criteria;

/**
* @author Ricardo Guerra
*/
public interface GenericDAO{

public void save(Object object);

public void saveObject(Object object);

public void updateObject( Object object );

public void delete(Object persistentInstance);

public Object findById( Class clazz, java.io.Serializable id);

public Object find( Class clazz, Long id );

public List findByObject(Object object);

public List findByExample(Object exampleInstance, String... excludeProperty);

public List findLikeExample(Object exampleInstance, String... excludeProperty);

public List findLikeExampleOrdered(Object exampleInstance, String[] orders,String... excludeProperty);

public List findLikeExampleOrdered (Object exampleInstance, List orders,String... excludeProperty );

public void deleteById(Class clazz, java.io.Serializable id);

public List findAll(Class clazz);

public List findAllClass();

public List getFindCriteria(Object object);

public List getFindCriteria(Object object, String ordenado);

public List getFindCriteria(Object object, String ordenado, String restringe);

public List getFindCriteria(Object object, int maxResults, String ordenado);

public List getFindCriteria(Object object, int maxResults);

public Criteria getCriteria(Object object);

public Criteria getCriteria(Object object, String ordenado);

public void initializeCollection(java.util.Collection collection);

public void initializeCollection2(Collection col);

public void initializeObject(Object o);

public void initialize(Object object);

public String getSequenceNextValue(String sequence );

public boolean exists(Class clazz,java.io.Serializable id);

public void saveCollection(java.util.Collection collection);

public void saveCollection2(java.util.Collection collection);

public void merge(Object object);

public void flush();

public void setNull(Object obj);
}


GenericDAOImpl.java

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.java.model.dao.generic.GenericDAO;
import org.java.model.util.Util;
import org.springframework.orm.hibernate3.HibernateQueryException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.apache.commons.lang.StringUtils;

/**
* @author Ricardo Guerra
*/

public class GenericDAOImpl extends HibernateDaoSupport implements GenericDAO{

private Logger logger = Logger.getLogger( this.getClass().getName() );


public GenericDAOImpl(){
}

public void save(Object object) {
logger.debug("saving instance");
try{
getHibernateTemplate().saveOrUpdate(object);
logger.debug("save successful");
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public void updateObject( Object object ) {
logger.debug("updating instance");

try{
getHibernateTemplate().update(object);
logger.debug("update successful");
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public void saveObject(Object object) {
logger.debug("saving instance");

try{
getHibernateTemplate().save(object);
logger.debug("save successful");
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public void delete(Object object) {
logger.debug("deleting instance");

try{
getHibernateTemplate().delete(object);
logger.debug("delete successful");
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public Object findById(Class clazz, java.io.Serializable id) {
logger.debug("getting instance with id: " + id+" from class: "+clazz.getName());

try{
Object instance = getHibernateTemplate().get(clazz, id);
return instance;
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public Object find( Class clazz, Long id ){
return getHibernateTemplate().load(clazz, id);
}

public List findByObject(Object object) {
logger.debug("getting instance with id: ");

try {
return getHibernateTemplate().findByExample(object);
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public List findByExample(Object exampleInstance, String... excludeProperty ){
try{
Criteria criteria = getSession().createCriteria(exampleInstance.getClass());
Example example = Example.create(exampleInstance).ignoreCase();

for( String exclude : excludeProperty ){
example.excludeProperty(exclude);
}
criteria.add(example);

return criteria.list();
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public List findLikeExample( Object exampleInstance, String... excludeProperty ){
try{
Criteria criteria = getSession().createCriteria( exampleInstance.getClass());
Example example = Example.create(exampleInstance).enableLike().ignoreCase();

for (String exclude : excludeProperty ){
example.excludeProperty(exclude);
}
criteria.add(example);
return criteria.list();
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public List findLikeExampleOrdered(Object exampleInstance, String[] orders,String... excludeProperty){

try{
Criteria criteria = getSession().createCriteria(exampleInstance.getClass());
Example example = Example.create(exampleInstance).enableLike().ignoreCase();

for (String exclude : excludeProperty) {
example.excludeProperty(exclude);
}
for (String order : orders) {
criteria.addOrder(Order.asc(order));
}
criteria.add(example);

return criteria.list();
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}


public List findLikeExampleOrdered (Object exampleInstance, List orders,String... excludeProperty ){

try{
Criteria criteria = getSession().createCriteria(exampleInstance.getClass());
Example example = Example.create(exampleInstance).enableLike().ignoreCase();

for( String exclude : excludeProperty) {
example.excludeProperty(exclude);
}
for( String order : orders) {
criteria.addOrder(Order.asc(order));
}
criteria.add(example);
return criteria.list();
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

private List findByExample(Object exampleInstance, boolean soloActivos, String... excludeProperty) {
if( !soloActivos ){
//String [] arr = {"estado"};
excludeProperty[excludeProperty.length] = "estado";
}
return findByExample(exampleInstance, excludeProperty);
}

public void deleteById(Class clazz, java.io.Serializable id) {
logger.debug("deleting instance with id: " + id+" from class: " + clazz.getName());

try{
Object object2 = this.findById(clazz, id);
getHibernateTemplate().delete(object2);
logger.debug("delete successful");
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public List findAll(Class clazz) {
logger.debug("getting instances from class : " + clazz.getName());
List list = null;

try{
list = getHibernateTemplate().find("from " + clazz.getSimpleName());
logger.debug("Find result: " + list.size() + " objects");
return list;
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public List findAllClass() {
logger.debug("getting instances from class ");
List list = null;

try{
list = getHibernateTemplate().find("from Object");
logger.debug("Find result: " + list.size() + " objects");
return list;
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public List getFindCriteria(Object object) {
List list = null;

try{
Criteria c = getCriteria(object);
List list2 = c.list();
list = new ArrayList(list2);
}
catch( HibernateException e ){
e.printStackTrace();
throw getHibernateTemplate().convertHibernateAccessException(e);
}
logger.debug("Find result: " + list.size() + " objects");
return list;
}

public Criteria getCriteria( Object object ) {

try{
this.setNull(object);

Criteria criteria = getSession().createCriteria( object.getClass() );
Example example = Example.create(object).enableLike(MatchMode.ANYWHERE).ignoreCase().excludeZeroes();
criteria.add(example);

return criteria;
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public List getFindCriteria(Object object, String ordenado) {
List list = null;

try{
this.setNull(object);
list = (List) getCriteria(object, ordenado).list();
}
catch (HibernateException e) {
e.printStackTrace();
throw getHibernateTemplate().convertHibernateAccessException(e);
}
logger.debug("Find result: " + list.size() + " objects");
return list;
}

public Criteria getCriteria(Object object, String ordenado) {
this.setNull(object);
Criteria criteria = getCriteria(object);
criteria.addOrder(Order.asc(ordenado));
return criteria;
}

public void setNull(Object obj) {
try{
if (obj != null) {
Field fields[] = obj.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; ++i) {
fields[i].setAccessible(true);
if (fields[i].getType().getName().equals("java.lang.Long")) {
Long valor = (Long) fields[i].get(obj);
if (fields[i].get(obj) != null
&& valor.longValue() == 0) {
fields[i].set(obj, null);
}
}
if (fields[i].getType().getName()
.equals("java.lang.String")
|| fields[i].getType().getName().equals(
"java.util.Date")) {
if (fields[i].get(obj) != null
&& fields[i].get(obj).equals("")) {
fields[i].set(obj, null);
}
}
}
}
}
catch (Exception e) {
logger.error("error al setear null :" + e.getMessage());
}
}

public void initializeCollection( Collection collection ){
try{
Hibernate.initialize(collection);
Iterator it=collection.iterator();

while(it.hasNext()){
Hibernate.initialize(it.next());
}
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public void initialize(Object obj){
Hibernate.initialize(obj);
}

public boolean exists(Class clazz,Serializable id){
return getHibernateTemplate().get(clazz,id)!=null;
}

public void saveCollection(Collection collection){
try{
java.util.Iterator it=collection.iterator();

while(it.hasNext()){
save(it.next());
}
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public void flush() {
logger.debug("flush");

try{
getHibernateTemplate().flush();
logger.debug("flush successful");
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public List getFindCriteria(Object object, int maxResults, String ordenado) {
List list = null;

try{
Criteria criteria = null;
this.setNull(object);

if( StringUtils.isEmpty(ordenado)){
criteria = getCriteria(object);
}
else{
criteria = getCriteria(object, ordenado);
}
criteria.setMaxResults(maxResults);
list = (List) criteria.list();
}
catch(HibernateException e) {
logger.error(e.getMessage(), e);
throw getHibernateTemplate().convertHibernateAccessException(e);
}
catch( RuntimeException e ){
logger.error(e.getMessage(), e);
throw e;
}
logger.debug("Find result: " + list.size() + " objects");
return list;
}

private Criteria getCriteria(Object object, String ordenado, String restringeNull) {
try{
Criteria criteria = getCriteria(object,ordenado);

if(!StringUtils.isEmpty(restringeNull)){
String[] rn=restringeNull.split(",");
for(int i=0;i criteria.add(Restrictions.isNull(rn[i]));
}
}
return criteria;
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public List getFindCriteria(Object object, String ordenado, String restringeNull) {
List list=(List) getCriteria(object,ordenado,restringeNull);
return list;
}

public List getFindCriteria(Object object, int maxResults) {
return getFindCriteria(object,maxResults,null);
}

/**
* Metodo para obtener el valor siguiente para un secuencia
* @param sequence
* @return String
*/
public String getSequenceNextValue( String sequence ){
String resultado = "0" ;
String sql = "SELECT " + sequence + ".NEXTVAL FROM DUAL";

List result = getSession().createSQLQuery(sql).list();

if( Util.collectioEnabled(result) ){
resultado = String.valueOf(result.get(0));
}

return resultado;
}

public void initializeCollection2(Collection col){
if( col != null ){
Hibernate.initialize(col);
Iterator it=col.iterator();

while(it.hasNext()){
Object obj = it.next();
initializeObject(obj);
}
}
}

public void initializeObject(Object o){
Hibernate.initialize(o);
//Configuration a = new Configuration();
//Iterator i = a.getClassMappings();
for( Field campo:o.getClass().getDeclaredFields() ){
Object tr = new Object();

try{
Method getter = org.springframework.beans.BeanUtils.findDeclaredMethodWithMinimalParameters(o.getClass(), Util.getNombreGetter(campo));
if (getter!=null) {
tr = getter.invoke(o, null);
}
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}

Hibernate.initialize(tr);
}
}

public void merge(Object object) {
logger.debug("saving instance");

try{
getHibernateTemplate().merge(object);
logger.debug("merge successful");
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}

public void saveCollection2(Collection collection){

try{
java.util.Iterator it=collection.iterator();

while(it.hasNext()){
save(it.next());
}
}
catch( HibernateQueryException e ){
logger.error("The Error is: ", e );
throw e;
}
catch( RuntimeException e ){
logger.error("The Error is: ", e );
throw e;
}
}
}

GenericService.java

import java.util.Collection;
import java.util.List;
import org.hibernate.Criteria;

/**
* @author Ricardo Guerra
*/
public interface GenericService{


public void save(Object object);

public void saveObject(Object object);

public void updateObject( Object object );

public void delete(Object persistentInstance);

public Object findById( Class clazz, java.io.Serializable id);

public Object find( Class clazz, Long id );

public List findByObject(Object object);

public List findByExample(Object exampleInstance, String... excludeProperty);

public List findLikeExample(Object exampleInstance, String... excludeProperty);

public List findLikeExampleOrdered(Object exampleInstance, String[] orders,String... excludeProperty);

public List findLikeExampleOrdered (Object exampleInstance, List orders,String... excludeProperty );

public void deleteById(Class clazz, java.io.Serializable id);

public List findAll(Class clazz);

public List findAllClass();

public List getFindCriteria(Object object);

public List getFindCriteria(Object object, String ordenado);

public List getFindCriteria(Object object, String ordenado, String restringe);

public List getFindCriteria(Object object, int maxResults, String ordenado);

public List getFindCriteria(Object object, int maxResults);

public Criteria getCriteria(Object object);

public Criteria getCriteria(Object object, String ordenado);

public void initializeCollection(java.util.Collection collection);

public void initializeCollection2(Collection col);

public void initializeObject(Object o);

public void initialize(Object object);

public String getSequenceNextValue(String sequence );

public boolean exists(Class clazz,java.io.Serializable id);

public void saveCollection(java.util.Collection collection);

public void saveCollection2(java.util.Collection collection);

public void merge(Object object);

public void flush();

public void setNull(Object obj);
}


GenericServiceImpl.java

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import org.hibernate.Criteria;
import org.java.model.dao.generic.GenericDAO;
import org.java.model.service.generic.GenericService;

/**
* @author Ricardo Guerra
*/
public class GenericServiceImpl implements GenericService{

private GenericDAO genericDAO;


//Constructor...
public GenericServiceImpl(){
}

public GenericDAO getGenericDAO() {
return genericDAO;
}

public void setGenericDAO(GenericDAO genericDAO) {
this.genericDAO = genericDAO;
}

public void save(Object object){
this.genericDAO.save(object);
}

public void saveObject(Object object) {
this.genericDAO.saveObject( object );
}

public void updateObject(Object object) {
this.genericDAO.updateObject( object );
}

public void delete(Object object) {
this.genericDAO.delete(object);
}

public Object findById(Class clazz, Serializable id) {
Object obj = genericDAO.findById(clazz,id);
return obj;
}

public Object find( Class clazz, Long id ){
Object obj = genericDAO.find(clazz,id);
return obj;
}

public List findByObject(Object object) {
List lista = (List)genericDAO.findByObject(object);
return lista;
}

public List findByExample(Object exampleInstance, String... excludeProperty) {
return genericDAO.findByExample(exampleInstance, excludeProperty);
}

public List findLikeExample(Object exampleInstance, String... excludeProperty) {
return genericDAO.findLikeExample(exampleInstance, excludeProperty);
}

public List findLikeExampleOrdered( Object exampleInstance, String[] orders, String... excludeProperty ){
return genericDAO.findLikeExampleOrdered( exampleInstance, orders, excludeProperty);
}

public List findLikeExampleOrdered( Object exampleInstance, List orders, String... excludeProperty ){
return genericDAO.findLikeExampleOrdered( exampleInstance, orders, excludeProperty);
}

public void deleteById(Class clazz, Serializable id) {
this.genericDAO.deleteById(clazz, id);
}

public List findAll( Class clazz ){
List lista = this.genericDAO.findAll(clazz);
return lista;
}

public List findAllClass(){
List lista = this.genericDAO.findAllClass();
return lista;
}

public List getFindCriteria(Object object) {
List lista = this.genericDAO.getFindCriteria(object);
return lista;
}

public List getFindCriteria(Object object, String ordenado) {
List lista = this.genericDAO.getFindCriteria(object,ordenado);
return lista;
}

public Criteria getCriteria(Object object) {
Criteria lista = this.genericDAO.getCriteria(object);
return lista;
}

public Criteria getCriteria(Object object, String ordenado) {
Criteria lista = this.genericDAO.getCriteria(object, ordenado);
return lista;
}

public void setNull(Object obj){
this.genericDAO.setNull(obj);
}

public void initializeCollection(Collection collection){
this.genericDAO.setNull(collection);
}

public void initialize(Object obj){
this.genericDAO.setNull(obj);
}

public boolean exists( Class clazz, java.io.Serializable id){
return genericDAO.exists(clazz,id);
}

public void saveCollection(Collection collection){
this.genericDAO.saveCollection(collection);
}

public void flush(){
this.genericDAO.flush();
}

public List getFindCriteria(Object object, String ordenado,String restringe) {
List lista = this.genericDAO.getFindCriteria(object,ordenado, restringe);
return lista;
}

public List getFindCriteria(Object object, int maxResults, String ordenado) {
List lista = this.genericDAO.getFindCriteria(object, maxResults, ordenado);
return lista;
}

public List getFindCriteria( Object object, int maxResults ){
List lista = this.genericDAO.getFindCriteria( object, maxResults );
return lista;
}

public String getSequenceNextValue( String sequence ){
String secuencia = this.genericDAO.getSequenceNextValue( sequence );
return secuencia;
}

public void initializeCollection2(Collection col) {
this.genericDAO.initializeCollection2(col);
}

public void initializeObject(Object obj) {
this.genericDAO.initializeObject( obj );
}

public void merge(Object object) {
this.genericDAO.merge( object );
}

public void saveCollection2(Collection collection) {
this.genericDAO.saveCollection2( collection );
}
}

4 comentarios:

Diego dijo...

Hola cesar algo tarde para hacer un comentario, pero buenoEstoy arrancando con esto y no entiendo bien el funcionamiento de lo siguiente:
public void deleteById(Class clazz, Serializable id) {
this.genericDAO.deleteById(clazz, id);
}
Cual es el rol del parametro Class clazz, y al invocarlo como lo debo invocar.
Espero tu respuestas desde muchas gracias.
Saludo Diego desde Tandil - Bs As - Argentina-

JAVAMAN dijo...

Que tal Diego lo que pasa es que esa Clase GenericDao la utilizo al momento del trabajo con Hibernate. Su veneficio es que te brinda una coleción de metodos para la manipulación de clases Java Maestras (Previamente mapeadas) para los populares CRUD (Create, Update, Delete, entre otros), osea ya no se tendria que codificar solo mandar los argumentos especificados para la manipulacion de la Persistencia. Tu pregunta va referente a los argumentos que utiliza como datos de entrada. Bueno esas clases como usan teoria de Reflexion (Ver mi post sobre ese tema), para manejar dinamismo se le manda solo el class y el id. Ejm:

deleteById( Usuario.class, 2 );

te eliminar de tu tabla usuarios el del codigo 2.

Diego dijo...

Buenisimo, muchas gracias JAVAMAN, voy a seguir mirando tu blog, saludos desde Acá.

JAVAMAN dijo...

oks tio suerte...!!!