-
-
Save HiroNakamura/4048906 to your computer and use it in GitHub Desktop.
| package org.pruebasgwt.modelo; | |
| import java.util.List; | |
| import org.hibernate.HibernateException; | |
| import org.hibernate.Session; | |
| import org.hibernate.Transaction; | |
| import org.pruebasgwt.hibernate.Empleado; | |
| import org.pruebasgwt.hibernate.HibernateUtil; | |
| /** | |
| * | |
| * @author fernando | |
| */ | |
| public class EmpleadoDAO { | |
| private Session sesion; | |
| private Transaction tx; | |
| public long guardaEmpleado(Empleado empleado) throws HibernateException | |
| { | |
| long id = 0; | |
| try | |
| { | |
| iniciaOperacion(); | |
| id = (Long) sesion.save(empleado); | |
| tx.commit(); | |
| } catch (HibernateException he) | |
| { | |
| manejaExcepcion(he); | |
| throw he; | |
| } finally | |
| { | |
| sesion.close(); | |
| } | |
| return id; | |
| } | |
| public void actualizaEmpleado(Empleado empleado) throws HibernateException | |
| { | |
| try | |
| { | |
| iniciaOperacion(); | |
| sesion.update(empleado); | |
| tx.commit(); | |
| } catch (HibernateException he) | |
| { | |
| manejaExcepcion(he); | |
| throw he; | |
| } finally | |
| { | |
| sesion.close(); | |
| } | |
| } | |
| public void eliminaEmpleado(Empleado empleado) throws HibernateException | |
| { | |
| try | |
| { | |
| iniciaOperacion(); | |
| sesion.delete(empleado); | |
| tx.commit(); | |
| } catch (HibernateException he) | |
| { | |
| manejaExcepcion(he); | |
| throw he; | |
| } finally | |
| { | |
| sesion.close(); | |
| } | |
| } | |
| public Empleado obtenEmpleado(long idEmpleado) throws HibernateException | |
| { | |
| Empleado empleado = null; | |
| try | |
| { | |
| iniciaOperacion(); | |
| empleado = (Empleado) sesion.get(Empleado.class, idEmpleado); | |
| } finally | |
| { | |
| sesion.close(); | |
| } | |
| return empleado; | |
| } | |
| public List<Empleado> obtenListaEmpleados() throws HibernateException | |
| { | |
| List<Empleado> listaEmpleados = null; | |
| try | |
| { | |
| iniciaOperacion(); | |
| listaEmpleados = sesion.createQuery("from Empleado").list(); | |
| } finally | |
| { | |
| sesion.close(); | |
| } | |
| return listaEmpleados; | |
| } | |
| private void iniciaOperacion() throws HibernateException | |
| { | |
| sesion = HibernateUtil.getSessionFactory().openSession(); | |
| tx = sesion.beginTransaction(); | |
| } | |
| private void manejaExcepcion(HibernateException he) throws HibernateException | |
| { | |
| tx.rollback(); | |
| throw new HibernateException("Ocurrió un error en la capa de acceso a datos", he); | |
| } | |
| } |
package org.pruebasgwt.hibernate;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
/**
-
Hibernate Utility class with a convenient method to get Session Factory
-
object.
* -
@author fernando
*/
public class HibernateUtil {private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
public class Main
{
public static void main(String[] args)
{
ContactoDAO contactosDAO = new ContactosDAO();
Contacto contactoRecuperado = null;
long idAEliminar = 0;
//Creamos tes instancias de Contacto
Contacto contacto1 = new Contacto("Contacto 1", "contacto1@contacto.com", "12345678");
Contacto contacto2 = new Contacto("Contacto 2", "contacto2@contacto.com", "87654321");
Contacto contacto3 = new Contacto("Contacto 3", "contacto3@contacto.com", "45612378");
//Guardamos las tres instancias, guardamos el id del contacto1 para usarlo posteriormente
idAEliminar = contactosDAO.guardaContacto(contacto1);
contactosDAO.guardaContacto(contacto2);
contactosDAO.guardaContacto(contacto3);
//Modificamos el contacto 2 y lo actualizamos
contacto2.setNombre("Nuevo Contacto 2");
contactosDAO.actualizaContacto(contacto2);
//Recuperamos el contacto1 de la base de datos
contactoRecuperado = contactosDAO.obtenContacto(idAEliminar);
System.out.println("Recuperamos a " + contactoRecuperado.getNombre());
//Eliminamos al contactoRecuperado (que es el contacto3)
contactosDAO.eliminaContacto(contactoRecuperado);
//Obtenemos la lista de contactos que quedan en la base de datos y la mostramos
List<Contacto> listaContactos = contactosDAO.obtenListaContactos();
System.out.println("Hay " + listaContactos.size() + "contactos en la base de datos");
for(Contacto c : listaContactos)
{
System.out.println("-> " + c.getNombre());
}
}
}
package org.pruebasgwt.client;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.utilidad.hibernate.SessionFactory;
import org.pruebasgwt.hibernate.Usuarios;
/**
*
-
@author fernando
*/
public class UsuariosDAO2 {UsuariosDAO2(){
}public static Usuarios obtenerUsuario(int id)throws HibernateException{
Session session = null;
Transaction tx = null;
session = SessionFactory.getSession();
Usuarios usuario=null;try{ tx = session.beginTransaction(); Query q = session.createQuery("from Usuarios where id_usuario=:id"); q.setLong("id",id); usuario = (Usuarios) q.uniqueResult(); }catch(HibernateException ex){ if (tx != null) { tx.rollback(); } throw ex; } finally { session.close(); } return usuario;}
public static void main(String ... args){
Usuarios user=null;
UsuariosDAO2 dao=new UsuariosDAO2();
try{
user= (Usuarios) dao.obtenerUsuario(10);
System.out.println("nombre: "+user.getNombUs().toString());
}catch(Exception ex){
ex.printStackTrace(System.err);
}
}
}// funciona mejor esta clase
package org.pruebasgwt.hibernate;
// Generated 8/11/2012 04:58:40 PM by Hibernate Tools 3.2.1.GA
import java.math.BigDecimal;
/**
Empleado generated by hbm2java
*/
public class Empleado implements java.io.Serializable {
private Integer id;
private Departamento departamento;
private String nombre;
private BigDecimal sueldo;
public Empleado() {
}
public Empleado(Departamento departamento, String nombre, BigDecimal sueldo) {
this.departamento = departamento;
this.nombre = nombre;
this.sueldo = sueldo;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Departamento getDepartamento() {
return this.departamento;
}
public void setDepartamento(Departamento departamento) {
this.departamento = departamento;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public BigDecimal getSueldo() {
return this.sueldo;
}
public void setSueldo(BigDecimal sueldo) {
this.sueldo = sueldo;
}
}