Ejemplos de JPA - Guia #1


http://wiki.netbeans.org/SimpleJPAApplicationWithNetbeans


EJEMPLO DE JPA
==============

1. Crear Enterprise Application (AppGestionPersona) [desmarcar Create EJB module y Create web app module]

2. Crear dominio con nombre Dominio.java (java application), desmarcar "Create Main Class" [Agregar el CODIGO 0]

3. Crear paquete uy.edu.ort.dominio (en el proyecto creado anteriormente)

4. Crear clase Persona dentro del paquete recien creado.

5. Crear un modulo EJB (Nombre: AppGestionPersonaPersistencia-ejb) y agregarlo al enterprise application creado anteriormente.

6. Agregar la libreria EclipseLink (click derecho en Libraries dentro del EJB y Add Library...)

7. Agregar el mysql-connector-java-5.1.13-bin.jar (click derecho en Libraries dentro del EJB y Add JAR/Folder...)

8. Agregar el proyecto Dominio (click derecho en Libraries dentro del EJB y Add Project... y elegir Dominio)

9. Crear la base de datos en MySql (nombre prueba1)

10. Crear una conexion a la base de datos:
      Click en la ficha Services
      Click derecho en Databases / New Connection
      Elegir el driver MySql
      Poner los parametros de acceso a la bd (usuario root, pwd root, y el nombre de la base de datos  prueba1)

11. Crear un Persistence Unit (Click derecho sobre AppGestionPersonaPersistencia-ejb, New / Other / Persistence

12. Ponerle nombre GestionPersonaPU y elegir como Persistence Provider: EclipseLink (JPA...)

13. En data source, poner New Data Source...

14. Ponerle nombre: jdbc/prueba

15. En el combo de Database Connection, elegir la conexion creada anteriormente

16. En Table Generation Strategy marcar Drop and Create

[[PARA BORRAR CONEXIONES YA EXISTENTES:
  a. Editar el archivo glassfish-resources.xml (ubicado dentro de la carpeta setup de la ruta donde esta el ejb)
        b. Borrar la linea que dice jdbc-resource...
c. Ir al Enterprise Beans, en la ficha Services, en Databases, ubicar la conexion, hacerle Disconnect y luego borrarla.
]]


CREACION DEL ENTITY BEAN
========================

17. Crear un paquete uy.edu.ort.gestion.persona.entidades (click derecho sobre el ejb, New / Java Package... y luego Finish)

18. Sobre el paquete recien creado, boton derecho, New / Entity Class, y en class name, poner PersonaEntity

19. Editar el PersonaEntity.java recien creado y agregar este codigo en los imports (arriba del todo):
import javax.persistence.Table;
import javax.persistence.Column;

20. Agregar el codigo de la Entity Personas [CODIGO 1]


CREACION DEL SESION BEAN
========================

21. Crear el paquete uy.edu.ort.gestion.persona.negocio (click derecho sobre el ejb, New / Java Package... y luego Finish)

22. Crear un session bean PersonaSB, de tipo Stateless e interfaz Local (click derecho en el paquete creado en el paso anterior, New /
Session Bean)

23. ESTE PASO CREA DOS FUENTES: PersonaSB.java y PersonaSBLocal.java. Este ultimo es la interfaz.

24. Agregar el codigo a la interfaz (PersonaSBLocal.java) [CODIGO 2] (OBSERVAR EN EL CODIGO QUE HAY QUE HACER UN IMPORTS
DE LA CLASE PERSONA, PORQUE SINO NO SE PUEDE USAR EL OBJETO PERSONA)

25. Agregar el codigo al Session Bean (PersonaSB.java). [CODIGO 3]


CREACION DEL WEB SERVICE
========================

EN ESTE PASO SE CREA UN WEB SERVICE A PARTIR DE LOS METODOS DEL SESSION BEAN

26. Crear el paquete uy.edu.ort.gestion.persona.ws (click derecho sobre el EJB, New / Java Package... y luego Finish)

27. Click derecho en el paquete recien creado, New / Web Service

28. Ponerle nombre PersonaWS

29. Marcar Create Web Service from Existing Session Bean y luego dar Browse, y elegir PersonaSB (esto crea el codigo automaticamente en
base a lo que tenga el Session Bean)


DEPLOY
======

30. Click derecho sobre la Enterprise Application (AppGestionPersona) y luego Clean and Build.

Si dice BUILD SUCCESSFUL...

31. Click derecho sobre la AppGestionPersona, y luego DEPLOY.

VERIFICACION DEL DEPLOY
=======================

Para ver si el deploy quedo bien:

32. Abrir el administrador de glassfish (http://localhost:4848) [LOCALHOST O LA DIRECCION DONDE ESTE EL SERVIDOR GLASSFISH!!]

33. Click en Applications... Tiene que aparecer AppGestionPersona

34. Click en AppGestionPersona

35. Click en View Endpoint (abajo a la derecha)

36. Click en /PersonaWS/PersonaWS?Tester

37. Click en http://direccion_que_aparezca:8080/PersonaWS/PersonaWS?Tester


[CREAR UN CLIENTE PARA PROBAR LA APLICACION]

38. Crear un paquete dentro de ClientePrueba que se llame uy.edu.ort.cliente

39. Crear un nuevo proyecto en NetBeans (menu File / New Project / Java / Java Application)

40. Llamarlo ClientePrueba y dejar marcada la opcion "Create Main Class". En el nombre del main class poner uy.edu.ort.cliente.ClientePrueba (esto ya crea el paquete y deja el .java ahi adentro)

41. Agregar el [CODIGO 4]

42. Sobre el paquete donde esta el ClientePrueba.java, click derecho y crear un Cliente Web Service con la WSDL generada anteriormente [para saber la wsdl se puede ir al servidor glassfish]. Para esto marcar WSDL URL e indicar la url del wsdl:

http://localhost:8080/PersonaWS/PersonaWS?wsdl

[ESTA URL SE PUEDE VER EN EL ADMIN DE GLASSFISH]

43. Elegir el paquete donde estara el webservice (uy.edu.ort.cliente)

PARA PROBAR EL CLIENTE, CLICK DERECHO SOBRE ClientePrueba.java, y Run.




















[CODIGO 0]

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package uy.edu.ort.dominio;

/**
 *
 * @author CRUSSO_PC
 */
public class Persona {
    private long id;
    private String nombre;
    private String apellido;
    private String direccion;
 
    public String getNombre() {
        return nombre;
    }
 
    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
 
    public String getApellido(){
        return apellido;
    }
 
    public void setApellido(String apellido) {
        this.apellido = apellido;
    }
 
    public String getDireccion(){
        return direccion;
    }
 
    public void setDireccion(String direccion)
    {
        this.direccion = direccion;
    }
}

[FIN DEL CODIGO 0]




[CODIGO 1]
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package uy.edu.ort.gestion.persona.entidades;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * @author CRUSSO_PC
 */
@Entity
@Table(name="PERSONAS")
public class PersonaEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="ID")
    private Long id;

    @Column(name="NOMBRE", nullable=false)
    private String nombre;

    @Column(name="APELLIDO", nullable=false)
    private String apellido;
 
    @Column(name="DIRECCION", nullable=false)
    private String direccion;
     
    public Long getId() {
        return id;
    }

    public String getNombre(){
        return nombre;
    }
 
    public void setNombre(String nombre){
        this.nombre = nombre;
    }
 
    public String getApellido(){
        return apellido;
    }
 
    public void setApellido(String apellido){
        this.apellido = apellido;      
    }
 
    public String getDireccion() {
        return direccion;      
    }
 
    public void setDireccion(String direccion){
        this.direccion = direccion;
    }
 
    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof PersonaEntity)) {
            return false;
        }
        PersonaEntity other = (PersonaEntity) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "uy.edu.ort.gestion.persona.entidades.PersonaEntity[ id=" + id + " ]";
    }
 
}
[FIN CODIGO 1]


[CODIGO 2]
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package uy.edu.ort.gestion.persona.negocio;

import javax.ejb.Local;
import uy.edu.ort.dominio.Persona;

/**
 *
 * @author CRUSSO_PC
 */
@Local
public interface PersonaSBLocal {
    public void alta(Persona persona);
    public void eliminar(Persona persona);
    public void modificar(Persona persona);  
}

[FIN DEL CODIGO 2]


[CODIGO 3]
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package uy.edu.ort.gestion.persona.negocio;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import uy.edu.ort.dominio.Persona;
import uy.edu.ort.gestion.persona.entidades.PersonaEntity;

/**
 *
 * @author CRUSSO_PC
 */
@Stateless
public class PersonaSB implements PersonaSBLocal {
    @PersistenceContext
    EntityManager em;
 
    @Override
    public void alta(Persona persona)
    {
        PersonaEntity personaEntity = new PersonaEntity();
        personaEntity.setDireccion(persona.getDireccion());
        personaEntity.setNombre(persona.getNombre());
        personaEntity.setApellido(persona.getApellido());
        em.persist(personaEntity);
    }
 
    @Override
    public void eliminar(Persona persona)
    {      
    }

    @Override
    public void modificar(Persona persona)
    {      
    }

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
}

[FIN DEL CODIGO 3]




[CODIGO 4]
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package uy.edu.ort.cliente;

/**
 *
 * @author CRUSSO_PC
 */
public class ClientePrueba {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        PersonaWS port = new PersonaWS_Service().getPersonaWSPort();
     
        Persona persona = new Persona();
     
        persona.setDireccion("Lejos");
        persona.setNombre("Juan");
        persona.setApellido("Perez");
     
        port.alta(persona);
     
        System.out.println("Fin!!");
    }
 
}

[FIN DEL CODIGO 4]



No hay comentarios:

Publicar un comentario