CRUD

Siguiendo con el aprendizaje de JAVA, en este artículo veremos la estructura para la creación de un CRUD JAVA EE haciendo uso de HibernatePrimefaces y Mysql en un entorno JAVA WEB o JAVA EE, como primera instancia veamos la estructura que debe tener nuestro proyecto JAVA WEB:

CRUD JAVA EE Hibernate PrimeFaces Mysql

CRUD

Proyecto CRUD

 

También veamos las librerías que necesitaremos para desplegar la aplicación:

Librerias JAVA

A continuación veamos el código para cada uno de los archivos del proyecto, cabe decir que puede que vallas obteniendo errores a causa de la ausencia del código en otros archivos, veamos:

Nuestro archivo WEB.XML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
< ?xml version=»1.0″ encoding=»UTF-8″?>
<web -app version=»3.0″ xmlns=»http://java.sun.com/xml/ns/javaee» xmlns:xsi=»http://www.w3.org/2001/XMLSchema-instance» xsi:schemaLocation=»http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd»>
<context -param>
<param -name/>javax.faces.PROJECT_STAGE
<param -value/>Production
</context>
<servlet>
</servlet><servlet -name>Faces Servlet</servlet>
<servlet -class>javax.faces.webapp.FacesServlet</servlet>
<load -on-startup>1</load>

<servlet -mapping>
</servlet><servlet -name>Faces Servlet</servlet>
<url -pattern>/faces/*</url>

<session -config>
</session><session -timeout>
30
</session>

<welcome -file-list>
</welcome><welcome -file>faces/mostrar.xhtml</welcome>

<context -param>
<param -name/>primefaces.THEME
<param -value/>start
</context>

</web>

Nuestro archivo principal mostrar.xhtml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
< ?xml version=’1.0′ encoding=’UTF-8′ ?>
< !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://xmlns.jcp.org/jsf/facelets»
xmlns:p=»http://primefaces.org/ui»
xmlns:h=»http://xmlns.jcp.org/jsf/html»
xmlns:f=»http://xmlns.jcp.org/jsf/core»>

<body>
<ui:composition template=»./template.xhtml»>
<ui:define name=»content»>
<p:growl id=»msg» showDetail=»true»></p:growl>
<h:form id=»frmdata»>
<p:datatable id=»prueba» var=»prueba» value=»#{PruebaBean.prueba}» emptyMessage=»No se encontraron datos» rows=»10″ paginator=»true»>

<p:column headerText=»id»>
<h:outputtext value=»#{prueba.id}»></h:outputtext>
</p:column>

<p:column headerText=»nombres»>
<h:outputtext value=»#{prueba.nombres}»></h:outputtext>
</p:column>

<p:column headerText=»apellidos»>
<h:outputtext value=»#{prueba.apellidos}»></h:outputtext>
</p:column>

<p:column headerText=»telefono»>
<h:outputtext value=»#{prueba.telefono}»></h:outputtext>
</p:column>

<p:column headerText=»ciudad»>
<h:outputtext value=»#{prueba.ciudad}»></h:outputtext>
</p:column>

<p:column style=»width: 100px»>
<p:commandbutton id=»btnUpdate» update=»:frmModificar:display» oncomplete=» PF(‘usuarioDialogUpdate’).show()»
image=»ui-icon ui-icon-search»>
<f:setpropertyactionlistener value=»#{prueba}»
target=»#{PruebaBean.selectPrueba}»></f:setpropertyactionlistener>
</p:commandbutton>
<p:commandbutton id=»btnDelete» update=»:frmEliminar» oncomplete=»PF(‘usuarioDialogDelete’).show()»
image=»ui-icon ui-icon-trash»>
<f:setpropertyactionlistener value=»#{prueba}»
target=»#{PruebaBean.selectPrueba}»></f:setpropertyactionlistener>
</p:commandbutton>
</p:column>

<f:facet name=»footer»>
<p:commandbutton value=»Crear Usuario» oncomplete=»PF(‘pruebaDialogCreate’).show();»
update=»:frmCreate» icon=»ui-icon-document» style=»right: 40px;»>
</p:commandbutton>
<!–            <p:commandButton value=»Subir Ficheros» icon=»ui-icon-document» onclick=»javascript:window.location = ‘subir.xhtml'» >
–>
</f:facet>

</p:datatable>

</h:form>

<h:form id=»frmCreate»>
<p:dialog header=»Crear Usuario» widgetVar=»pruebaDialogCreate» resizable=»false» width=»330″ id=»dlgUsuarioCreate»  showEffect=»face» hideEffect=»explode» modal=»true»>
<h:panelgrid id=»display» columns=»2″ cellpadding=»4″>
<h:outputtext value=»Nombres: «></h:outputtext>
<p:inputtext value=»#{PruebaBean.selectPrueba.nombres}» style=»text-transform: uppercase;» onkeyup=»javascript:this.value.toUpperCase();»></p:inputtext>
<h:outputtext value=»Apellidos: «></h:outputtext>
<p:inputtext value=»#{PruebaBean.selectPrueba.apellidos}» style=»text-transform: uppercase;» onkeyup=»javascript:this.value.toUpperCase();»></p:inputtext>
<h:outputtext value=»Telefono: «></h:outputtext>
<p:inputtext value=»#{PruebaBean.selectPrueba.telefono}» style=»text-transform: uppercase;» onkeyup=»javascript:this.value.toUpperCase();»></p:inputtext>
<h:outputtext value=»Ciudad: «></h:outputtext>
<p:inputtext value=»#{PruebaBean.selectPrueba.ciudad}» style=»text-transform: uppercase;» onkeyup=»javascript:this.value.toUpperCase();»></p:inputtext>
</h:panelgrid>
<p:separator></p:separator>
<f:facet name=»footer»>
<p:commandbutton id=»btnCreateAceptar» update=»:frmdata :msg» actionListener=»#{PruebaBean.CrearPersona()}» oncomplete=»PF(‘pruebaDialogCreate’).hide()» value=»Guardar» image=»ui-icon-document»></p:commandbutton>
<p:commandbutton id=»btnSalirAceptar» update=»:frmdata :msg» oncomplete=»PF(‘pruebaDialogCreate’).hide()» value=»Salir» image=»ui-icon-document»></p:commandbutton>
</f:facet>
</p:dialog>
</h:form>

<h:form id=»frmModificar»>
<p:dialog header=»Modificar Registro» widgetVar=»usuarioDialogUpdate» resizable=»false»
id=»dlgUsuarioUpdate» showEffect=»face» hideEffect=»explode» modal=»true»>
<h:panelgrid id=»display» columns=»4″ cellpadding=»4″>
<h:outputtext value=»Id:»></h:outputtext>
<p:inputtext value=»#{PruebaBean.selectPrueba.id}»></p:inputtext>

<h:outputtext value=»Nombres:»></h:outputtext>
<p:inputtext value=»#{PruebaBean.selectPrueba.nombres}»
style=»text-transform: uppercase;» onkeyup=»javascript:this.value = this.value.toUpperCase();»></p:inputtext>

<h:outputtext value=»Apellidos»></h:outputtext>
<p:inputtext value=»#{PruebaBean.selectPrueba.apellidos}»
style=»text-transform: uppercase;» onkeyup=»javascript:this.value = this.value.toUpperCase();»></p:inputtext>

<h:outputtext value=»Telefono»></h:outputtext>
<p:inputtext value=»#{PruebaBean.selectPrueba.telefono}»
style=»text-transform: uppercase;» onkeyup=»javascript:this.value = this.value.toUpperCase();»></p:inputtext>

<h:outputtext value=»Ciudad»></h:outputtext>
<p:inputtext value=»#{PruebaBean.selectPrueba.ciudad}»
style=»text-transform: uppercase;» onkeyup=»javascript:this.value = this.value.toUpperCase();»></p:inputtext>

</h:panelgrid>

<p:separator></p:separator>
<f:facet name=»footer»>
<p:commandbutton id=»btnActualizarAceptar» update=»:frmdata :msg» oncomplete=»PF(‘usuarioDialogUpdate’).hide();»
actionListener=»#{PruebaBean.updateEmpleado()}» value=»Modificar» image=»ui-icon-document»></p:commandbutton>
<p:commandbutton id=»btnActualizarSalir» update=»:frmdata :msg» oncomplete=»PF(‘usuarioDialogUpdate’).hide();»
value=»Salir» image=»ui-icon-document»></p:commandbutton>

</f:facet>

</p:dialog>

</h:form>

<h:form id=»frmEliminar»>
<p:confirmdialog id=»idconfirmDialog» message=»En realidad desea eliminar este registro?»
header=»Eliminar Registro» widgetVar=»usuarioDialogDelete»>
<h:inputhidden value=»#{PruebaBean.selectPrueba.id}»></h:inputhidden>
<p:commandbutton id=»btnAceptar» value=»Aceptar» update=»:frmdata :msg» actionListener=»#{PruebaBean.deleteEmpleado()}» oncomplete=»PF(‘usuarioDialogDelete’).hide();»></p:commandbutton>
<p:commandbutton id=»btnCancelar» value=»Cancelar» update=»:frmdata :msg» oncomplete=»PF(‘usuarioDialogDelete’).hide();»></p:commandbutton>
</p:confirmdialog>
</h:form>

</ui:define>
</ui:composition>
</body>
</html>

Veamos el archivo template.xhtml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
< ?xml version=’1.0′ encoding=’UTF-8′ ?>
< !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://xmlns.jcp.org/jsf/facelets»
xmlns:h=»http://xmlns.jcp.org/jsf/html»>

<h:head>
<meta http-equiv=»Content-Type» content=»text/html; charset=UTF-8″ />
<h:outputstylesheet name=»./css/default.css»></h:outputstylesheet>
<h:outputstylesheet name=»./css/cssLayout.css»></h:outputstylesheet>
<title>CRUD JAVAEE</title>
</h:head>

<h:body>
<div id=»top» class=»ui-widget-header ui-corner-all»>
<ui:insert name=»top»>CRUD JAVAEE – BYSPEL</ui:insert>
</div>
<div id=»content» class=»center_content»>
<ui:insert name=»content»>Content</ui:insert>
</div>

</h:body>

</html>

Ahora estableceremos los parametros de conexión en el archivo hibernate.cfg.xml.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
< ?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»>
<hibernate -configuration>
<session -factory>
<property name=»hibernate.dialect»>org.hibernate.dialect.MySQLDialect</property>
<property name=»hibernate.connection.driver_class»>com.mysql.jdbc.Driver</property>
<property name=»hibernate.connection.url»>jdbc:mysql://localhost:3306/personas</property>
<property name=»hibernate.connection.username»>root</property>
<property name=»hibernate.connection.password»></property>
<property name=»hibernate.show_sql»>true</property>
<property name=»hibernate.current_session_context_class»>thread</property>
<mapping class=»entidades.Prueba»></mapping>
</session>
</hibernate>

Posteriormente mediante el archivo hibernate.reveng.xml se mapea la base de datos y nuestra tabla:

1
2
3
4
5
6
< ?xml version=»1.0″ encoding=»UTF-8″?>
< !DOCTYPE hibernate-reverse-engineering PUBLIC «-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN» «http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd»>
<hibernate -reverse-engineering>
<schema -selection match-catalog=»personas»></schema>
<table -filter match-name=»usuarios»></table>
</hibernate>

Ahora el archivo PruebaBean donde se encuentran las acciones a realizar. como la búsqueda de registros, actualización, eliminación y creación:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
* 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 bean;

import dao.pruebaDAO;
import entidades.Prueba;
import impl.PruebaDaoImpl;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

/**
*
* @author IdlhDeveloper
*/
@ManagedBean(name = «PruebaBean»)
@RequestScoped
public class PruebaBean {
private Prueba selectPrueba;
private List<prueba> prueba;

/**
* Creates a new instance of PruebaBean
*/
public PruebaBean() {
this.selectPrueba = new Prueba();
this.prueba = new ArrayList</prueba><prueba>();
}

public Prueba getSelectPrueba() {
return selectPrueba;
}

public void setSelectPrueba(Prueba selectPrueba) {
this.selectPrueba = selectPrueba;
}

public List</prueba><prueba> getPrueba() {
pruebaDAO dao = new PruebaDaoImpl();
this.prueba = dao.findAll();
return prueba;
}

public void setPrueba(List</prueba><prueba> prueba) {
this.prueba = prueba;
}
public void CrearPersona(){
pruebaDAO dao = new PruebaDaoImpl();
String msg = null;
if(dao.create(selectPrueba)){
msg = «El registro fué creado con éxito!»;
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null);
FacesContext.getCurrentInstance().addMessage(null, message);
}else{
msg = «Error Creando el Registro en la Base de datos»;
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null);
FacesContext.getCurrentInstance().addMessage(null, message);

}
}
public void updateEmpleado() {
pruebaDAO dao = new PruebaDaoImpl();
String msg;
if (dao.update(this.selectPrueba)) {
msg = «Los datos se actualizaron correctamente»;
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null);
FacesContext.getCurrentInstance().addMessage(null, message);
} else {
msg = «Error Modificando el registro»;
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
public void deleteEmpleado(){
pruebaDAO dao = new PruebaDaoImpl();
String msg;
if (dao.delete(this.selectPrueba.getId())) {
msg = «El empleado fue eliminado con exito!»;
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null);
FacesContext.getCurrentInstance().addMessage(null, message);
} else {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, null, null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
}
</prueba>

Nuestra interface mediante el archivo pruebaDAO:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
* 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 dao;

import entidades.Prueba;
import java.util.List;

/**
*
* @author IdlhDeveloper
*/
public interface pruebaDAO {
public List<prueba> findAll();
public boolean create(Prueba prueba);
public boolean update(Prueba prueba);
public boolean delete(Integer id);
}
</prueba>

Ahora nuestra entidad (Tabla de la base de datos) mapeada, con estos valores pueden crear la estructura de la tabla en su BD:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* 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 entidades;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
*
* @author IdlhDeveloper
*/
@Entity
@Table(name = «usuarios»)
public class Prueba {
@Id
@GeneratedValue
@Column(name = «id»)
private Integer id;

private String nombres;
private String apellidos;
private String telefono;
private String ciudad;

public Prueba(){
this.id=0;

}

public Integer getId() {
return id;
}

public void setId(Integer 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 getTelefono() {
return telefono;
}

public void setTelefono(String telefono) {
this.telefono = telefono;
}

public String getCiudad() {
return ciudad;
}

public void setCiudad(String ciudad) {
this.ciudad = ciudad;
}
}

Implementamos todos los métodos haciendo uso del archivo PruebaDaoImpl:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
* 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 impl;

import dao.pruebaDAO;
import entidades.Prueba;
import java.util.List;
import org.hibernate.Session;
import util.HibernateUtil;

/**
*
* @author IdlhDeveloper
*/
public class PruebaDaoImpl implements pruebaDAO{

@Override
public List<prueba> findAll() {
List</prueba><prueba> listado = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
String sql = «from Prueba»;
try {
session.beginTransaction();
listado = session.createQuery(sql).list();
session.beginTransaction().commit();
} catch (Exception e) {
session.beginTransaction().rollback();
}
return listado;
}

@Override
public boolean create(Prueba prueba) {
boolean flag;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
session.save(prueba);
flag = true;
} catch (Exception e) {
System.out.println(«Error: » + e.getMessage());
flag = false;
session.beginTransaction().rollback();
}
return flag;
}

@Override
public boolean update(Prueba prueba) {
boolean flag;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
session.load(Prueba.class, prueba.getId());
session.update(prueba);
flag = true;
} catch (Exception e) {
System.out.println(«Error «+e.getMessage());
flag = false;
session.beginTransaction().rollback();
}
return flag;
}

@Override
public boolean delete(Integer id) {
boolean flag;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
Prueba prueba=(Prueba) session.load(Prueba.class, id);
session.delete(prueba);
session.beginTransaction().commit();
flag = true;
} catch (Exception e) {
flag = false;
session.beginTransaction().rollback();
}
return flag;
}

}
</prueba>

Ahora nuestro HibernateUtil, si usas netbeans puedes generarlo dando clic sobre la carpeta Web Pages, seleccionas nuevo, a continuación otro y en la sección Hibernate Encontraras HibernateUtil:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
* 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 util;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
* Hibernate Utility class with a convenient method to get Session Factory
* object.
*
* @author IdlhDeveloper
*/
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;
}
}

Luego podemos realizar el deploy de la aplicación haciendo clic derecho sobre el proyecto y a continuación delpoy, con lo cual estará lista para ver desde nuestro navegador en mi caso:
http://localhost:8080/CRUD/

Obteniendo como resultado una interfaz como la expuesta al principio del artículo, cualquier duda no olvides dejarla en los comentarios.

Hasta pronto!.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

×