How To Create A J2SE Spring-Hibernate Desktop App!!!
How To Create A J2SE Spring-Hibernate Desktop App!!!
Myeclipse
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Introduction
Espero esto te sirva como una guía para ayudarte en la creación de una aplicación simple que usa Spring y
Hibernate.
Este pequeño pero útil manual nos ayudará a comprender cómo se realiza una aplicación usando:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Configurando nuestra BD
Los siguientes son los pasos para configurar nuestra Base de
Datos.
System requirements
Dentro de los requerimientos que tendrá nuestra aplicación Spring & Hibernate están:
Instalando la BD
Lo primero que tenemos que hacer es arrancar nuestro manejador postgreSQL.
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Para hacerlo las instrucciones son las siguientes:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Veamos como se hace:
1. Establecerle un nombre.
2. Establecer el incremento para cada registro
3. Asignar el valor de inicio de la secuencia.
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Creación de nuesta tabla que usa la secuencia.
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Al finalizar, nos debe quedar un Script como el siguiente:
Listo, hasta este momento sólo tenemos una tabla con su secuencia.
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Ahora iremos un poco más rápido.
Después:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Configurando la aplicación en MyEclipse
Creando la aplicación en MyEclipse
Iniciemos..
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Después:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Y nos debe quedar esta estructura de archivos:
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
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
Desmarcar la opción:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Ahora debe quedarnos la siguiente estructura de archivos:
Agregando Spring
Agregando Hibernate Framework a nuestro proyecto.
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Activar la opción
· Dejar activas las opciones que ya se encuentran seleccionadas
· Hibernate 3.2 Advanced Support Libraries.
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Elegir la opción:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
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
agregar uno vea el tema: Agregar un DB Driver.
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
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
La siguiente imagen nos muestra cómo es que queda la última pantalla del asistente:
Por ultimo presionamos Finish
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
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 debemos
de hacer es lo siguiente:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
DEBEREMOS CREAR UN NUEVO PAQUETE PARA TODO LO QUE GENERAREMOS, por ejemplo:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
· Java Data Access Object (DAO) (Hibernate only)
· *Generate precise findBy methods
Y POR ULTIMO:
· DAO Type: Basic DAO
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
En la siguiente página debemos
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
De modo que quede de la siguiente manera:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
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
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Eso nos tuvo que generar un esquema de archivos como este:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Organizando el código
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
Creando nuestra clase Demo.java
Clase Demo
Para crear la clase que nos permitirá interactuar directamente sobre nuestra BD debemos dar click
derecho 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
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
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
/**
* @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á un
error:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
class="sequence"></generator> escribir el nombre de la secuencia como lo muestro abajo de manera
correcta.
FRAGMENTO ERRONEO:
FRAGMENTO CORRECTO:
Una vez corregidos estos detalles ahora si podremos perctarnos que todo salió correcto:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
El cual nos dice que hay una violación al UNIQUE CONSTRAINT para el campo nombre, ya que como
recordaremos 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
Apendices
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 y
seleccionamos la opción New
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
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
Luego probamos que nuestro driver sea correcto, y para finalizar veremos una pantalla como la
siguiente:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
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">
<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
</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();
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
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
return configuration;
}
Archivos hbm.xml
NOTA: obervar que el archivo hibernate.cfg.xml en sus tags mapping resources tenga la ubicación
correcta de los archivos en los paquetes que dicen estar.
Inicialmente era:
Created with the Freeware Edition of HelpNDoc: Free CHM Help documentation generator
es claro no?
· Direccion.hbm.xml
· Persona.hbm.xml
"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