Mostrando entradas con la etiqueta Hibernate. Mostrar todas las entradas
Mostrando entradas con la etiqueta Hibernate. Mostrar todas las entradas

jueves, 8 de marzo de 2012

INTEGRACIÓN - SPRING 3 + HIBERNATE 3 + SERVLET + MAVEN

Que tal compañeros regreso a postear luego de algún tiempo y en esta oportunidad hablare y mostrare otra forma de cómo integrar el Framework HIBERNATE.

Si hablamos un poco de este Framework es uno de los Frameworks orientados a persistencia mas utilizados por las diferentes ventajas que nos brinda.

El ejemplo posteado esta principalmente orientado a mostrar la correcta integración de dicho Framework HIBERNATE 3, al ser integrado con otro framework SPRING 3. Para fines del Dummy la ejecución se realizara por medio de un SERVLET y la arquitectura del APP será construida mediante MAVEN.


Este proyecto demo esta orientado a Web y fue desarrollado en la IDE Spring Suite v2.5 que es en si un ECLIPSE con varios PLUGINs adicionales y la ejecución del proyecto en si esta controlado con MAVEN y soportado en la BD DB_PLANTILLA en MYSQL Script dentro del Resources .

EJECUCION:

La ejecución de los ejemplos se desencadenaran mediante la ejecución del SERVLET: ValidaHibernateServlet . Estos son los siguientes:

- obtenerUsuarioForma01
- obtenerListaUsuarios2
- obtenerListaUsuarios3
- obtenerObjetoUsuarios
- registarUsuarioProducto


Finalmente, se puede comentar que el Dummy muestra las diferentes formas de como manejar HIBERNATE ya en lo que respecta al manejo de Sesiones y el uso del popular Generic DAO .

Para descargar el ejemplo completo descargarlo de: AQUÌ.

sábado, 28 de agosto de 2010

INTEGRACION: HIBERNATE + MAVEN + JDBC

Que tal compañeros regreso a postear luego de algún tiempo y en esta oportunidad hablare y mostrare un ejemplo de como manejar el Framework Hibernate .

Si hablamos un poco de este Framework es uno de los Frameworks orientados a persistencia mas utilizados por las diferentes ventajas que nos brinda.

Facilidad para el manejo transaccional de distintas bases de datos, ya que este Framework es de tipo ORM (Object Relational Mappin) , esto hace que el Framework realice un el mapeo completo de la base de datos relacional utilizada, en archivos XMLs (Uno por cada Bean creado) los mapeos y clases generadas expresan herencia y polimorfismo y creando una base de datos orientada a objetos. Esto hace que al momento de la creación de los Querys no nos preocupemos por la DB utilizada ya que dicho Query servirá para cualquier Base de datos ya que el acceso a los datos los puedes manejar de distintas formas utilizando ESQL y CRITERIA.

El ejemplo posteados esta principalmente orientado a mostrar el manejo del Framework Hibernate manejando un patrón DAO para facilitar el acceso a persistencia. Adicionalmente, el ejemplo realiza las mismas operaciones de persistencia realizadas con Hibernate con JDBC, a modo que se vea un comparativo del manejo de persistencia.

Este proyecto demo esta orientado a Web y fue desarrollado en la IDE JBOSS Developer Studio v2.0 que es en si un ECLIPSE con varios PLUGINs adicionales y la ejecución del proyecto en si esta controlado con Maven. (Para los que no conocen Maven entrar aquí: ) y soportado en la BD SAMPLE que viene cargada dentro de DERBY. (Una versión de Derby viene ya integrado con en al descarga de la IDE NetBeans) , facilitando la inicialización de la BD desde el mismo NetBeans.

EJECUCION:

La ejecución de los ejemplos preparados están realizados en JUnit-Test (Click derecho + Run ass + JUnit Test) y son los siguientes:

- TestConexionJdbc
- TestObjetoClienteJdbc
- TestListaObjetosClienteJdbc
- TestObjetoClienteHibernate
- TestListaObjetosClienteHibernate

Finalmente, en la clase pe.com.crga.framework.java.impl.ClienteDaoHibernate se muestra 3 formas distintas del manejo de Hibernate para las operaciones manejadas (Solo se descomenta la deseada) .

Para descargar el ejemplo completo descargarlo de: AQUÌ.

sábado, 9 de mayo de 2009

Validaciones con Hibernate Annotations & RichFaces

Explorando una forma nueva de realizar las validaciones, comence a indagar como podria realizarlo por medio de Anotaciones con el Framework 'Hibernate' y bueno probando resulto el demo preparado a continuaciòn.

Este demo esta realizado en Eclipse, Maven y RichFaces (Para el acceso a las anotaciones, mediante uno de sus controles). Para los que no puedan correr la aplicacion por medio de Maven, aqui esta un muy buen tutorial descargable.

Para descargar la aplicaciòn demo pulsar:
Aquì.

viernes, 16 de enero de 2009

Hibernate Dialect

Aqui comparto los diferentes Dialecto que Hibernate utiliza, para su manejo de los diferentes motores de datos. Estos son:


A.- DB2 - org.hibernate.dialect.DB2Dialect

B.- HypersonicSQL - org.hibernate.dialect.HSQLDialect

C.- Informix - org.hibernate.dialect.InformixDialect

D.- Ingres - org.hibernate.dialect.IngresDialect

E.- Interbase - org.hibernate.dialect.InterbaseDialect

F.- Pointbase - org.hibernate.dialect.PointbaseDialect

G.- PostgreSQL - org.hibernate.dialect.PostgreSQLDialect

H.- Mckoi SQL - org.hibernate.dialect.MckoiDialect

I.- Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect

J.- MySQL - org.hibernate.dialect.MySQLDialect

K.- Oracle (Any Version) - org.hibernate.dialect.OracleDialect

L.- Oracle 9 - org.hibernate.dialect.Oracle9Dialect

M.- Progress - org.hibernate.dialect.ProgressDialect

Ñ.- FrontBase - org.hibernate.dialect.FrontbaseDialect

O.- SAP DB - org.hibernate.dialect.SAPDBDialect

P.- Sybase - org.hibernate.dialect.SybaseDialect

Q.- Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect


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 );
}
}

Integrando Spring 3 + Hibernate 3 + JSF + MAVEN

Hola a todos, hace ya algun tiempo que ya no posteo nada, ya que he
estado bien ocupado ultimamente, por eso motivo regreso aqui para compartirles
una aplicación J2EE demo donde muestro la integración que he realizado de los Frameworks: Spring 3 + Hibernate 3 + JSF + MAVEN.

El entorno en la que he trabajo es similar al del demo que postee
hace ya algun tiempo:

La aplicaciòn demo esta dividida en 2 carpetas:

Demo_Spring_Hibernate_Jsf: Que contiene todo el Proyecto Web en las carpetas 'src' y 'WebContent'. ( Las cuales las reemplazaras en un proyecto dinamico que crearas desde Eclipse ).

La aplicacion muestra un simple login en donde se genera una sesion de usuario que redirecciona hacia una interfaz de bienvenida, pero lo realmente interesante es la arquitectura segmentada, que se esta manejando para realizar dicho proceso.

Para descargar el demo pulsar: AQUI..

Para descargar el PDF "SIMILITUD: HQL vs CRITERIA" pulsar: AQUI..

sábado, 8 de noviembre de 2008

Integrando Spring 2.5 & Hibernate 3

Hola aquí les comparto mi aplicación demo donde muestra la integración que he realizado de los Frameworks: Spring 2.5 & Hibernate 3.
El entorno en la que he trabajo cuenta con lo siguiente:

- IDE: Red Hat Developer Studio 1.0.0.CR1
(http://www.jboss.com/products/devstudio)
Que integra un Eclipse 3.3 con una seria de plugins muy útiles como:
JBoss Application Server
Hibernate Tools
JSF Tools, etc. Y un entorno de diseño que para mi es el mejor.

- Plataforma: JAVA 6
- Frameworks: Spring 2.5 - Hibernate 3
- Motor de Datos: MySql Server 5.0

Explicación Ràpida:
El demo al ejecutarse muestra el resultado en consola de tres registros devueltos por tres listas y un bean devuelto por un objeto de la base de datos. El demo esta en base a un proyecto JAVA de tipo Web Dinámico, en donde he creado una Arquitectura que permita segmentar correctamente las Capas, Daos y Servicios respectivos. Si bien el demo no lo he hecho para Web (Esta Vez), la arquitectura que se maneja esta preparada para ser utilizada de esta manera (En un próximo demo mostrare ello).

Aquí estoy utilizando Spring 2.5 para el manejo de la capa de negocio y Hibernate 3 para lo que es la capa de persistencia. Asimismo, se esta manejando los populares y muy útiles Generic Dao. Además, en el ejemplo se muestra dentro de la clase (UsuarioDAOImpl.java), las diferentes formas de cómo manipular las transacciones en base al manejo de sesiones por medio de Hibernate 3 (métodos: obtenerUsuarioForma01 y obtenerUsuarioForma02) y por medio de Spring 2.5 (método: obtenerUsuarioForma03). Finalmente, la conexión en la aplicación la estoy manejando vía JDBC en base a 2 archivos:

• jdbc.properties (para Spring).
• hibernate.cfg.xml (para Hibernate).

Además, he puesto dentro de la carpeta DataBase el script de la base de datos que estoy utilizando, dentro de la carpeta lib del proyecto todas las librerías necesarias, para que simplemente importen el proyecto, en el Build-Path acomoden el JDK respectivo y listo. Finalmente, hay dos archivos dentro de la carpeta 'Otros':

• Driver_Url_JDBC: Muestra los diferentes Drives y URL para conexiones JDBC para diferentes motores de Datos.
• HibernateDialect: Muestra los diferentes Dialectos Hibernate para diferentes motores de Datos.

Para descargar la aplicacion Demo, pulsar AQUI..
Para descargar las librerias base del Demo, pulsar AQUI.

Espero que les haya gustado el demo preparado y ya estaré colgando en estos días este mismo ejemplo pero orientado netamente a Web y unido con otro Framework JSF.


Foto Aplicacion #1


Foto Aplicacion #2


Foto Aplicacion #3


Para descargar el PDF "SIMILITUD: HQL vs CRITERIA" pulsar: AQUI..