Está en la página 1de 20

Cómo crear un CRUD en Java Web en Eclipse

con JSF, JPA, Maven


MI REPOSITORIO: https://github.com/escm1990/JSF_JPA_CRUD

Descarga de GitHub (proyecto videos tutoriales): https://github.com/elivarl/CRUD-Java-Web-JSF-JPA

1. Cómo crear un CRUD en Java Web en Eclipse con JSF, JPA, Maven (Configuración Proyecto)
https://youtu.be/6CKih16kPPE

2. Cómo crear un CRUD en Java Web JSF, JPA, Maven (Base de Datos y persistencexml)
https://youtu.be/dp06qVE48n0

3. Cómo crear un CRUD en Java Web con JSF, JPA, Maven (Creacion del Modelo y la clase JPAUtil)
https://youtu.be/_oqeKZK7ess

4. Cómo crear un CRUD en Java Web JSF, JPA, Maven (Clase ClienteDAO)
https://youtu.be/flRPj_J7rWo

5. Cómo crear un CRUD en Java Web JSF , JPA, Maven (Paso de información al index)
https://youtu.be/GWvbtFoZ9M0

6. Cómo crear un CRUD en Java Web JSF, JPA, Maven (Mostrar registros Clientes)
https://youtu.be/EXYsN6oZnu4

7. CRUD Java Web JSF, JPA, Maven (Editar registros)


https://youtu.be/-oyaQ__9Y8s

8. CRUD Java Web JSF, JPA, Maven (Eliminar registros)


https://youtu.be/zi3DdMKHxbA

9. CRUD Java Web JSF, JPA, Maven (Crear un nuevo registro)


https://youtu.be/luS2KqD5nS0
1.CONFIGURACION

- Crear un proyecto Maven nuevo


1
2

3
- Agregar las dependencias necesarias en el pom.xml y cambiar la versión del jdk (por defecto es 1.7)

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.prueba.jsf_jpa_crud</groupId>
<artifactId>JSF_JPA_CRUD</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>JSF_JPA_CRUD Maven Webapp</name>


<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->


<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.6.Final</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.3.6.Final</version>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->


<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->


<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.14</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.sun.faces/jsf-api -->


<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.17</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.sun.faces/jsf-impl -->


<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.17</version>
</dependency>
</dependencies>

<build>
<finalName>JSF_JPA_CRUD</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven
defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-
bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
- Clic derecho sobre el proyecto → Maven → Update Proyect (para que se agreguen los jar al proyecto)

- Menú Windows → Show View → Navegator , acá modificar el archivo mostrado, cambiando la
versión del “jst-web” de 2.3 a 3.1 (Esto cambiará la versión del Servlet)

- Modificar el descriptor del proyecto ( src/main/webapp/WEB-INF/web.xml)

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">

<display-name>Archetype Created Web Application</display-name>

<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>

<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>

- Clic derecho sobre el proyecto → Build Path → Configure Build Path y marcar Maven Dependencies.

- Crear archivo index.xhtml y correrlo sobre el servidor (en este caso Tomcat 9).
2. BASE DE DATOS Y PERSISTENCE.XML

Crear una nueva base de datos llamada “jsf_jpa_crud”, dentro crear una tabla llamada clientes

CREATE USER 'jsf_jpa_crud'@'localhost' IDENTIFIED BY 'jsf_jpa_crud';

GRANT ALL PRIVILEGES ON * . * TO 'jsf_jpa_crud'@'localhost';

FLUSH PRIVILEGES;

CREATE SCHEMA `jsf_jpa_crud` ;

CREATE TABLE `jsf_jpa_crud`.`clientes` (


`id` INT NOT NULL,
`nombres` VARCHAR(255) NULL,
`apellidos` VARCHAR(255) NULL,
`direccion` VARCHAR(255) NULL,
`email` VARCHAR(45) NULL,
`telefono` VARCHAR(45) NULL,
`fregistro` DATETIME NULL,
`factualizacion` DATETIME NULL,
PRIMARY KEY (`id`));

- Se va a crear el directorio META-INF en el proyecto.

- Dentro de este directorio, crear un archivo XML llamado persistence que es el que va a permitir la
conexión con la base de datos.
persistence.xml

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">

<persistence-unit name="PERSISTENCE">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://
localhost:3306/jsf_jpa_crud" />
<property name="javax.persistence.jdbc.user"
value="jsf_jpa_crud" />
<property name="javax.persistence.jdbc.password"
value="jsf_jpa_crud" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>

</persistence>
3. CREACION DEL MODELO y LA CLASE JPAUtil (Entity Manager Factory)

- Crear un paquete que contendrá nuestra clase modelo. Clic derecho en src/main/java y se creara un
paquete.

- Crear una clase dentro de ese paquete, esta hará de entidad referenciado a la tabla clientes.
package com.modelo;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity // la clase es interpretada como una entidad


@Table(name = "clientes") //nombre de la tabla en la base de datos
public class Cliente {

@Id //esta es la llave de la tabla


@GeneratedValue(strategy = GenerationType.IDENTITY) //campo
autoincrementable
private Long id;
@Column
private String nombres;
@Column
private String apellidos;
@Column
private String direccion;
@Column
private String email;
@Column
private String telefono;
@Temporal(TemporalType.TIMESTAMP) //reconozca el tipo date
private Date fregistro;
@Temporal(TemporalType.TIMESTAMP)
private Date factualizacion;

public Long getId() {


return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNombres() {
return nombres;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public Date getFregistro() {
return fregistro;
}
public void setFregistro(Date fregistro) {
this.fregistro = fregistro;
}
public Date getFactualizacion() {
return factualizacion;
}
public void setFactualizacion(Date factualizacion) {
this.factualizacion = factualizacion;
}
@Override
public String toString() {
return "Cliente [id=" + id + ", nombres=" + nombres + ", apellidos=" +
apellidos + ", direccion=" + direccion
+ ", email=" + email + ", telefono=" + telefono + ",
fregistro=" + fregistro + ", factualizacion="
+ factualizacion + "]";
}

}
- Crear la clase JPAUtil, esta permitirá crear el objeto para conectarse a la base de datos. Se creará en el
mismo paquete “model”.

package com.modelo;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class JPAUtil {

private static final String PERSISTENCE_UNIT_NAME = "PERSISTENCE";


private static EntityManagerFactory factory;

public static EntityManagerFactory getEntityManagerFactory() {


if(factory==null) {
factory =
Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
}
return factory;
}

public static void shutdown() {


if (factory != null) {
factory.close();
}
}
}
4. CLASE “CLIENTEDAO” - Contrendrá las operaciones CRUD para la tabla clientes

- Se creará un nuevo paquete a nivel del paquete model. Dentro de esta se crea la clase ClienteDAO

package com.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.modelo.Cliente;
import com.modelo.JPAUtil;

public class ClienteDAO {

// Los metodos CRUD estarán apoyados por Hibernate. Por ello se crea
un objeto EntityManager.
EntityManager entity =
JPAUtil.getEntityManagerFactory().createEntityManager();

// Definicion de los metodos CRUD

//Guardar, recibe como parametro un objeto cliente, que es el que se


va a persistir.
public void guardar(Cliente cliente) {
entity.getTransaction().begin(); // Se indica que se inicia una
transacción.
entity.persist(cliente); // Guarda el objeto cliente en la base
de datos.
entity.getTransaction().commit(); // Se indica que se cierra la
transacción.
//JPAUtil.shutdown(); // Cierra la conexión a la base de datos.
}

//Editar, recibe como parametro un objeto cliente, que es el que se va


a persistir.
public void editar(Cliente cliente) {
entity.getTransaction().begin(); // Se indica que se
inicia una transacción.
entity.merge(cliente); // Actualiza el objeto cliente en
la base de datos.
entity.getTransaction().commit(); // Se indica que se
cierra la transacción.
//JPAUtil.shutdown(); // Cierra la conexión a la base de
datos.
}

//Eliminar
public void eliminar(Long id) {
Cliente c = new Cliente();
c = entity.find(Cliente.class, id);
entity.getTransaction().begin();
entity.remove(c);
entity.getTransaction().commit();
}

// Buscar cliente
public Cliente buscar(Long id) {
Cliente c = new Cliente();
c = entity.find(Cliente.class, id); //La clase base del
objeto a obtener, y el id del registro a obtener
//JPAUtil.shutdown(); // Cierra la conexión a la base de
datos.
return c;
}

// Obtener todos los clientes


@SuppressWarnings("unchecked")
public List<Cliente> obtenerClientes(){
List<Cliente> listaClientes = new ArrayList<>();
Query q = entity.createQuery("SELECT c FROM Cliente c");
//JAQL - parecido a SQL, administrado por Hibernate
listaClientes = q.getResultList();
return listaClientes;
}
}
5. PASO DE INFORMACION AL INDEX (ManagedBean)

- Crear un nuevo paquete a la altura de model y dao, se llamara “controller” y dentro de este se crea una
nueva clase llamada “ClienteBean”.

6. MOSTRAR REGISTROS CLIENTES – utilizando DAO

ClienteBean.java

package com.controller;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import com.dao.ClienteDAO;
import com.modelo.Cliente;

@ManagedBean (name = "clienteBean")


@RequestScoped
public class ClienteBean {

public List<Cliente> obtenerClientes(){


ClienteDAO clienteDAO = new ClienteDAO();
return clienteDAO.obtenerClientes();
}
}

Index.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/


TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="es" xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">

<h:head></h:head>
<h:body>
<h2><h:outputText value="Lista Clientes" /></h2>

<h:dataTable border="1" value="#{clienteBean.obtenerClientes()}"


var="cliente">
<h:column>
<f:facet name="header">ID</f:facet>
<h:outputText value="#{cliente.id}" />
</h:column>

<h:column>
<f:facet name="header">Nombres</f:facet>
<h:outputText value="#{cliente.nombres}" />
</h:column>

<h:column>
<f:facet name="header">Apellidos</f:facet>
<h:outputText value="#{cliente.apellidos}" />
</h:column>

<h:column>
<f:facet name="header">Direccion</f:facet>
<h:outputText value="#{cliente.direccion}" />
</h:column>

<h:column>
<f:facet name="header">Email</f:facet>
<h:outputText value="#{cliente.email}" />
</h:column>

<h:column>
<f:facet name="header">Telefono</f:facet>
<h:outputText value="#{cliente.telefono}" />
</h:column>

<h:column>
<f:facet name="header">F. Registro</f:facet>
<h:outputText value="#{cliente.fregistro}" />
</h:column>

<h:column>
<f:facet name="header">F. Actualizacion</f:facet>
<h:outputText value="#{cliente.factualizacion}" />
</h:column>

<h:column>
<f:facet name="header">Editar</f:facet>
<h:commandButton action="#{clienteBean.editar(cliente.id)}" value="Editar" /> <!--
Esta linea se agrega cuando se haya codificado el bean con el metodo editar-->
</h:column>
<h:column>
<f:facet name="header">Eliminar</f:facet>
<h:commandButton action="#{clienteBean.eliminar(cliente.id)}" value="Eliminar" />
</h:column>
</h:dataTable>
</h:body>
</html>

7. EDITAR REGISTROS

- En la clase ClienteBean.java se van a crear 2 métodos, uno para enviar el objeto cliente desde un
boton del index a la nueva vista llamada “editar.xhtml”. El otro metodo se usa para actualizar desde la
nueva vista los cambios en el cliente.

@SuppressWarnings("unused")
public String editar(Long id) {
ClienteDAO clienteDAO = new ClienteDAO();
Cliente c = new Cliente(); //en este objeto se va almacenar el objeto
que se va a buscar
c = clienteDAO.buscar(id);
System.out.println(c.toString());

//Crear una coleccion para enviarlo a la vista editar.xhtml


Map<String, Object> sessionMap =
FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
//se le pasa un parametro de tipo cadena ("cliente"), con este nombre
sera recibido en la vista
sessionMap.put("cliente", c);
return "editar.xhtml";
}

public String actualizar(Cliente cliente) {


ClienteDAO clienteDAO = new ClienteDAO();
clienteDAO.editar(cliente);
return "index.xhtml";
}

- Crear una nueva vista (editar.xhtml) para editar los registros. Este archivo se crea en la misma carpeta
que el index.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/


TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">

<h:head></h:head>
<h:body>

<h:form>
<h:panelGrid columns="2" cellspacing="20" border="1">
<f:facet name="header">
<h:outputLabel value="Editar Cliente" />
</f:facet>

<h:outputText value="Nombres" />


<h:inputText value="#{cliente.nombres}" />
<h:outputText value="Apellidos" />
<h:inputText value="#{cliente.apellidos}" />

<h:outputText value="Direccion" />


<h:inputText value="#{cliente.direccion}" />

<h:outputText value="Telefono" />


<h:inputText value="#{cliente.telefono}" />

<h:outputText value="Email" />


<h:inputText value="#{cliente.email}" />

<f:facet name="footer">
<h:commandButton value="Actualizar"
action="#{clienteBean.actualizar(cliente)}"/>
</f:facet>

</h:panelGrid>

</h:form>
</h:body>
</html>

8. ELIMINAR REGISTROS

- En la clase ClienteDAO, agregar el método eliminar el cliente

//Eliminar, se pasa como parametro el id del cliente a eliminar


public void eliminar(Long id) {
Cliente c = new Cliente();
c = entity.find(Cliente.class, id); //se busca el cliente
en base al parametro id. Se necesita la clase del objeto a buscar
entity.getTransaction().begin(); // Se indica que se
inicia una transacción.
entity.remove(c); // Elimina el objeto cliente en la base
de datos.
entity.getTransaction().commit(); // Se indica que se
cierra la transacción.
}

- En el ClienteBean, se procede a crear un método que elimine el cliente en base al id que se le


proporcione.

public String eliminar(Long id) {


ClienteDAO clienteDAO = new ClienteDAO();
clienteDAO.eliminar(id);
System.out.println("Cliente eliminado");
return "index.xhtml";
}

- En el index.xhtml, agregar el botón para llamar el metodo eliminar desde el ManagedBean.

<h:column>
<f:facet name="header">Eliminar</f:facet>
<h:commandButton action="#{clienteBean.eliminar(cliente.id)}" value="Eliminar" />
</h:column>
9. AGREGAR UN NUEVO REGISTRO

- En el index.xhtml, agregamos un boton para que nos redirija a una nueva vista (nuevo.xhtml). Este
debe estar DENTRO del form

<h:commandButton action="#{clienteBean.nuevo()}" value="Nuevo" />

- En el ClienteBean se crea el método nuevo() que nos redirija hacia la nueva vista.

public String nuevo() {


Cliente c = new Cliente();
Map<String, Object> sessionMap =
FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
//se le pasa un parametro de tipo cadena ("cliente"), con este nombre
sera recibido en la vista
sessionMap.put("cliente", c);
return "nuevo.xhtml";
}

- El código de la vista es el siguiente:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/


TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">

<h:head></h:head>
<h:body>
<h:form>
<h:panelGrid columns="2" cellspacing="20" border="1">
<f:facet name="header">
<h:outputText value="Nuevo Cliente"></h:outputText>
</f:facet>

<h:outputText value="Nombres"></h:outputText>
<h:inputText value="#{cliente.nombres}"></h:inputText>

<h:outputText value="Apellidos"></h:outputText>
<h:inputText value="#{cliente.apellidos}"></h:inputText>

<h:outputText value="Direccion"></h:outputText>
<h:inputText value="#{cliente.direccion}"></h:inputText>

<h:outputText value="Telefono"></h:outputText>
<h:inputText value="#{cliente.telefono}"></h:inputText>

<h:outputText value="Email"></h:outputText>
<h:inputText value="#{cliente.email}"></h:inputText>

<f:facet name="footer">
<h:commandButton action="#{clienteBean.guardar(cliente)}"
value="Guardar"></h:commandButton>
</f:facet>
</h:panelGrid>
</h:form>
</h:body>
</html>

- En el ClienteBean se crea el método guardar(cliente) y nos redirija al index.xhtml

public String guardar(Cliente c) {


ClienteDAO clienteDAO = new ClienteDAO();
clienteDAO.guardar(c);
System.out.println("Cliente guardado");
return "index.xhtml";
}

También podría gustarte