how to create a j2se spring-hibernate desktop app!!!

43
Spring Core and Hibernate on Myeclipse Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Upload: jose-said

Post on 08-Apr-2015

821 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: How to create a J2SE Spring-Hibernate Desktop App!!!

Spring Core and Hibernate on

Myeclipse

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 2: How to create a J2SE Spring-Hibernate Desktop App!!!

Introduction

Autor: José Said Olano GarcíaCorreo: [email protected]://java4said.blogspot.comSCJA, SCJP, SCWCD, SCBCD, SCMAD

Espero esto te sirva como una guía para ayudarte en la creación de una aplicación simple que usa Spring yHibernate.

Este pequeño pero útil manual nos ayudará a comprender cómo se realiza una aplicación usando:

· PostgreSQL como manejador de base de datos.· Spring framework para la capa de DAO y las operaciones de acceso a la BD.· Hibernate Framework como Mapeador de Objetos Relacional (ORM).

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 3: How to create a J2SE Spring-Hibernate Desktop App!!!

Configurando nuestra BD

Los siguientes son los pasos para configurar nuestra Base deDatos.

· Crear la Base de datos· Crear las secuencias necesarias· Crear las tablas necesarias.

System requirementsDentro de los requerimientos que tendrá nuestra aplicación Spring & Hibernate están:

· PosgreSQL 8.4 descargable de la página http://www.postgresql.org/download/

· Spring framework (Será agregado como una de las capacidades de nuestro proyecto Java)Pueden ver más información de este en su página: http://www.springsource.org

· Hibernate 3.2 framework (Será agregado como una de las capacidades de nuestro proyecto Java) http://www.hibernate.org/

Instalando la BDLo primero que tenemos que hacer es arrancar nuestro manejador postgreSQL.

Usando el programa pgAdmin III:

Después debemos crear nuestra base de datos:

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 4: How to create a J2SE Spring-Hibernate Desktop App!!!

Para hacerlo las instrucciones son las siguientes:

1. Acceder a nuestro servidor de Base de Datos (BD).2. Click derecho y elegir la opción new Database.3. Posteriormente, asignarle un nombre a la BD.4. Click en el botón Aceptar

Creando nuestra tablaPara crear nuestra tabla debemos hacer lo siguiente:

1. Crear la secuencia correspondiente para cada registro.2. Crear la tabla deseada y en su campo id agregarle el valor nextval ('nombreDeLaSecuencia').

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 5: How to create a J2SE Spring-Hibernate Desktop App!!!

Veamos como se hace:

Creación de una secuencia.

1. Establecerle un nombre.2. Establecer el incremento para cada registro3. Asignar el valor de inicio de la secuencia.

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 6: How to create a J2SE Spring-Hibernate Desktop App!!!

Creación de nuesta tabla que usa la secuencia.

Para crear nuestra tabla:1. Debemos ponerle un nombre.2. Ir a la pestaña SQL y desactivar la opción: Read Only3. Ahi podemos escribir definir manualmente nuestro comando DDL.4. Ojo: en nuestro campo id debemos poner el tipo de dato, si es o no null, la palabra DEFAULT y

acontinuación nextval('secuencia_persona').5. Esto ligará nuestra secuencia con nuestro database field.

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 7: How to create a J2SE Spring-Hibernate Desktop App!!!

Al finalizar, nos debe quedar un Script como el siguiente:

Listo, hasta este momento sólo tenemos una tabla con su secuencia.

creando una tabla detalle

Creación de una tabla detalle

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 8: How to create a J2SE Spring-Hibernate Desktop App!!!

Ahora iremos un poco más rápido.

Después:

y nos quedará una estructura de objetos similar a ésta:

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 9: How to create a J2SE Spring-Hibernate Desktop App!!!

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 10: How to create a J2SE Spring-Hibernate Desktop App!!!

Configurando la aplicación en MyEclipse

Creando la aplicación en MyEclipse

En este punto usaremos Spring y Hibernate.

Los pasos a seguir son:

1. Crear el proyecto Java.2. Agregar las capacidades Spring.3. Agregar un Driver de Base de datos (en caso de no tenerlo).4. Agregar las capacidades Hibernate.5. Organizar nuestro código.6. Crear la clase de prueba

Creando un proyecto Java

Creación de un Java Project

Les comparto una imagen de la instalación que tengo en mi pc de MyEclipse.

Iniciemos..

Click Derecho y elegir Java Project

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 11: How to create a J2SE Spring-Hibernate Desktop App!!!

Después:

· Asignarle un nombre al proyecto.· Elegir la versión de JDK que usaremos.

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 12: How to create a J2SE Spring-Hibernate Desktop App!!!

Y nos debe quedar esta estructura de archivos:

Listo hemos creado un simple proyecto Java vacio.

Agregando Spring

Agregando Spring Framework a nuestro proyecto.

Ahora veremos como se agrega soporte Spring a nuestro proyecto vacio java.

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 13: How to create a J2SE Spring-Hibernate Desktop App!!!

Los pasos son los siguientes:1. Click derecho sobre nuestro proyecto.2. Ir a la opción MyEclipse.3. Elegir la opción: Add Spring Capabilities

Elegir:· Spring 2.5 AOP· Spring 2.5 Core Libraries· Spring 2.5 Persistence Core Libraries

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 14: How to create a J2SE Spring-Hibernate Desktop App!!!

Desmarcar la opción:

Enable AOP builder

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 15: How to create a J2SE Spring-Hibernate Desktop App!!!

Ahora debe quedarnos la siguiente estructura de archivos:

Listo, ahora nuestro proyecto ya tiene las librerias Spring instaladas.

Agregando Spring

Agregando Hibernate Framework a nuestro proyecto.

Ahora veremos como se agrega soporte Hibernate a nuestro proyecto Java.

Los pasos son los siguientes:4. Click derecho sobre nuestro proyecto.5. Ir a la opción MyEclipse.6. Elegir la opción: Add Hibernate Capabilities

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 16: How to create a J2SE Spring-Hibernate Desktop App!!!

Activar la opción· Dejar activas las opciones que ya se encuentran seleccionadas· Hibernate 3.2 Advanced Support Libraries.

Nos debe quedar algo así:

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 17: How to create a J2SE Spring-Hibernate Desktop App!!!

Elegir la opción:

Hibernate configuration file (hibernate.cfg.xml)

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 18: How to create a J2SE Spring-Hibernate Desktop App!!!

Escribir algún nombre para nuestra clase SessionFactory a crear:

El siguiente paso es elegir nuestro Driver de BD. Nota: La primera vez no se cuenta con DB Drivers. Para

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 19: How to create a J2SE Spring-Hibernate Desktop App!!!

agregar uno vea el tema: Agregar un DB Driver.

La siguiente pantalla nos solicitará el nombre de nuestra SessionFactory:

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 20: How to create a J2SE Spring-Hibernate Desktop App!!!

Lo unico que haremos es crear un paquete para tener más ordenado nuestro código fuente.

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 21: How to create a J2SE Spring-Hibernate Desktop App!!!

La siguiente imagen nos muestra cómo es que queda la última pantalla del asistente:Por ultimo presionamos Finish

Ahora debe quedarnos la siguiente estructura de archivos:

Listo, ahora nuestro proyecto ya tiene las librerias Hibernate instaladas.

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 22: How to create a J2SE Spring-Hibernate Desktop App!!!

Mapeo de DB a Java

Mapeo de la Base de datos a Clases Java.

Para poder trabajar haciendo uso de Spring y Hibernate ( ya configurados previamente), lo que debemosde hacer es lo siguiente:

· En la pestaña DB Browser elegir la tabla que deseamos mapear a clase de Java.· Después elegir la opción: Hibernate Reverse Engineering

IMPORTANTE CUANDO TENGAMOS ESTA PANTALLA:

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 23: How to create a J2SE Spring-Hibernate Desktop App!!!

DEBEREMOS CREAR UN NUEVO PAQUETE PARA TODO LO QUE GENERAREMOS, por ejemplo:

Ahora si podemos continuar con las demás instrucciones.

Tenemos que dejar activas las opciones:· Create POJO<>DB Table mapping information· *Create a hibernate mapping file (*.hbm.xml for each database table)· * Update Hibernate configuration with mapping resource location.· Java Data Object <>DB Table· *Create abstract class

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 24: How to create a J2SE Spring-Hibernate Desktop App!!!

· Java Data Access Object (DAO) (Hibernate only)· *Generate precise findBy methods

Y POR ULTIMO:· DAO Type: Basic DAO

En la siguiente página deberemos elegir en el campo Id Generator: Sequence

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 25: How to create a J2SE Spring-Hibernate Desktop App!!!

En la siguiente página debemos

1.- Elegir el correcto IdGenerator: sequence para cada tabla.

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 26: How to create a J2SE Spring-Hibernate Desktop App!!!

De modo que quede de la siguiente manera:

Lo mismo para la siguiente tabla:

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 27: How to create a J2SE Spring-Hibernate Desktop App!!!

2.- Activar las 2 cajas de verificación:· Include referenced tables (A->B)· Include referencing tables (A<-B).

ASI MISMO COMO LAS 2 OPCIONES INFERIORES:· Generate support for ListedTable(fk)->UnlistedTable· Generate support for UnListedTable(fk)->ListedTable

Quedando de la siguiente manera:

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 28: How to create a J2SE Spring-Hibernate Desktop App!!!

Eso nos tuvo que generar un esquema de archivos como este:

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 29: How to create a J2SE Spring-Hibernate Desktop App!!!

Organizando el código

Organizando el código de una manera más ordenada podrías quedar así:

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 30: How to create a J2SE Spring-Hibernate Desktop App!!!

Creando nuestra clase Demo.java

Clase Demo

Para crear la clase que nos permitirá interactuar directamente sobre nuestra BD debemos dar clickderecho sobre nuestra proyecto Java, luego elegir la opción New, después Class

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 31: How to create a J2SE Spring-Hibernate Desktop App!!!

En la pantalla bastará que:· Elijamos un paquete· Nombre a nuestra clase· Generemos un método main.

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 32: How to create a J2SE Spring-Hibernate Desktop App!!!

Su código es el siguiente:

/** * */package com.mx.josesaid.tester;

import java.util.Calendar;

import org.hibernate.Transaction;

import com.mx.josesaid.codigo.dao.PersonaDAO;import com.mx.josesaid.codigo.pojos.Persona;import com.mx.josesaid.fabrica.HibernateSessionFactory;

/** * @author Administrator * */public class DemoMainClass {

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 33: How to create a J2SE Spring-Hibernate Desktop App!!!

/** * @param args */public static void main(String[] args) {

Transaction tx = HibernateSessionFactory.getSession().beginTransaction();

PersonaDAO personaDao = new PersonaDAO();Persona p = new Persona();p.setNombre("jose said");// p.setId(-1);p.setApellidopaterno("Olano");p.setApellidomaterno("Garcia");p.setEdad(27);java.sql.Timestamp fecha = new java.sql.Timestamp(Calendar

.getInstance().getTime().getTime());p.setFechanacimiento(fecha);personaDao.save(p);tx.commit();HibernateSessionFactory.getSession().close();System.out.println("listo");

}}

Este código tiene un detalle --> AL momento de insertar el registro nos mostrará unerror:

Esto debido a que en el Id Generator de cada tabla escribimos el valor sequenced.

Para corregirlo tenemos 2 opciones:

1. Crear en postgreSQL la secuencia hibernate_sequence:CREATE SEQUENCE hibernate_sequence INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 START 1 CACHE 1; 

2. ó en su defecto modificar cada uno de nuestros archivos hbm.xml y en el tag <generator

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 34: How to create a J2SE Spring-Hibernate Desktop App!!!

class="sequence"></generator> escribir el nombre de la secuencia como lo muestro abajo de maneracorrecta.

FRAGMENTO ERRONEO:

<id name="id" type="java.lang.Integer"> <column name="id" />

<generator class="sequence"></generator> </id>

FRAGMENTO CORRECTO:

<id name="id" type="java.lang.Integer"> <column name="id" />

<generator class="sequence"> <param name="sequence">secuencia_direccion</param>

</generator> </id>

Una vez corregidos estos detalles ahora si podremos perctarnos que todo salió correcto:

Ahora veamos en la base de datos como quedó insertado nuestro registro...

¿Que pasa si ejecutamos nuevamente nuestro código Java?

R = Obtenemos el siguiente error:

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 35: How to create a J2SE Spring-Hibernate Desktop App!!!

El cual nos dice que hay una violación al UNIQUE CONSTRAINT para el campo nombre, ya que comorecordaremos lo declaramos unico en nuestra base de datos, si no recuerdas observa:

Saludos....

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 36: How to create a J2SE Spring-Hibernate Desktop App!!!

Apendices

Agregar un DB Driver en MyEclipse

Cómo agregar un DB Driver en MyEclipse.

Veamos como se hace:

Dar click en el icono: para que nos despliegue una lista, de la cual seleccionaremos la opción:MyEclipse Database Explorer

Esto nos habilitará la pestaña en el IDE llamada DB Browser, en ésta damos click derecho yseleccionamos la opción New

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 37: How to create a J2SE Spring-Hibernate Desktop App!!!

y procederemos a llenar el formulario con los datos de nuestro servidor de base de datos.

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 38: How to create a J2SE Spring-Hibernate Desktop App!!!

Luego probamos que nuestro driver sea correcto, y para finalizar veremos una pantalla como lasiguiente:

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 39: How to create a J2SE Spring-Hibernate Desktop App!!!

Esto indica que todo salió perfectamente.

Archivo hibernate.cfg.xml

Archivo hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration>

<session-factory><property name="dialect">

org.hibernate.dialect.PostgreSQLDialect</property><property name="connection.url">

jdbc:postgresql://localhost:5432/java</property><property name="connection.username">postgres</property><property name="connection.password">said</property><property name="connection.driver_class">

org.postgresql.Driver</property><property name="myeclipse.connection.profile">

PostgreSQL_said</property><mapping resource="com/mx/josesaid/codigo/Persona.hbm.xml" /><mapping resource="com/mx/josesaid/codigo/Direccion.hbm.xml" />

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 40: How to create a J2SE Spring-Hibernate Desktop App!!!

</session-factory>

</hibernate-configuration>

Archivo HibernateSessionFactory.java

Archivo HibernateSessionFactory.java

package com.mx.josesaid.fabrica;

import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.cfg.Configuration;

/** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */public class HibernateSessionFactory {

/** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION;

static { try {

configuration.configure(configFile);sessionFactory = configuration.buildSessionFactory();

} catch (Exception e) {System.err

.println("%%%% Error Creating SessionFactory %%%%");e.printStackTrace();

} } private HibernateSessionFactory() { }

/** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen()) {if (sessionFactory == null) {

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 41: How to create a J2SE Spring-Hibernate Desktop App!!!

rebuildSessionFactory();}session = (sessionFactory != null) ? sessionFactory.openSession()

: null;threadLocal.set(session);

}

return session; }

/** * Rebuild hibernate session factory * */

public static void rebuildSessionFactory() {try {

configuration.configure(configFile);sessionFactory = configuration.buildSessionFactory();

} catch (Exception e) {System.err

.println("%%%% Error Creating SessionFactory %%%%");e.printStackTrace();

}}

/** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null);

if (session != null) { session.close(); } }

/** * return session factory * */

public static org.hibernate.SessionFactory getSessionFactory() {return sessionFactory;

}

/** * return session factory * * session factory will be rebuilded in the next call */

public static void setConfigFile(String configFile) {HibernateSessionFactory.configFile = configFile;sessionFactory = null;

}

/** * return hibernate configuration * */

public static Configuration getConfiguration() {

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 42: How to create a J2SE Spring-Hibernate Desktop App!!!

return configuration;}

}

Archivos hbm.xmlNOTA: obervar que el archivo hibernate.cfg.xml en sus tags mapping resources tenga la ubicacióncorrecta de los archivos en los paquetes que dicen estar.

Inicialmente era:

Pero al organizar el código y ponerlos dentro del paquete com.mx.josesaid.codigo.xml, la rutatambién deberá de ser actualizadas en las líneas 24 y 25 quedando de la siguiente manera:

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator

Page 43: How to create a J2SE Spring-Hibernate Desktop App!!!

es claro no?

Correciones a Archivos hbm.xmlDe igual manera sucede con los archivos

· Direccion.hbm.xml· Persona.hbm.xml

Los cuales inicialmente estaban en la ruta:

"com.mx.josesaid.codigo.Persona"y "com.mx.josesaid.codigo.Direccion respectivamente",

que ahora pasan a estar segun el arbol de directorios YA ORGANIZADO esta nueva ruta:

"com.mx.josesaid.codigo.pojos.Persona" y "com.mx.josesaid.codigo.pojos.Direccion"

Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator