No es un bug, es una característica no documentada

viernes, 12 de febrero de 2016

Acceso a datos. Hibernate. Ejercicios

0:51 Posted by Inazio Claver , , No comments
Antes de empezar los ejercicios deberás cargar el siguiente script en MySQL:









DROP DATABASE IF EXISTS EJEMPLO;
CREATE DATABASE EJEMPLO;
USE EJEMPLO;

-- -------------------------------------------------------------------------------------------
-- ----------------------------------------- MYSQL--------------------------------------------
--
-- TABLA DEPARTAMENTOS
--
CREATE TABLE departamentos (
 dept_no  TINYINT(2) NOT NULL PRIMARY KEY,
 dnombre  VARCHAR(15),
 loc      VARCHAR(15)
)ENGINE=InnoDB ;

INSERT INTO departamentos VALUES (10,'CONTABILIDAD','SEVILLA');
INSERT INTO departamentos VALUES (20,'INVESTIGACIÓN','MADRID');
INSERT INTO departamentos VALUES (30,'VENTAS','BARCELONA');
INSERT INTO departamentos VALUES (40,'PRODUCCIÓN','BILBAO');
COMMIT;
--
-- TABLA EMPLEADOS
--
CREATE TABLE empleados (
 emp_no    SMALLINT(4)  NOT NULL PRIMARY KEY,
 apellido  VARCHAR(10),
 oficio    VARCHAR(10),
 dir       SMALLINT,
 fecha_alt DATE      ,
 salario   FLOAT(6,2),
 comision  FLOAT(6,2),
 dept_no   TINYINT(2)
 -- CONSTRAINT FK_EMPLE_DEPART FOREIGN KEY (dept_no) REFERENCES departamentos(dept_no)
)ENGINE=InnoDB ;

INSERT INTO empleados VALUES (7369,'SÁNCHEZ','EMPLEADO',7902,'1990/12/17', 1040,NULL,20);
INSERT INTO empleados VALUES (7499,'ARROYO','VENDEDOR',7698,'1990/02/20', 1500,390,30);
INSERT INTO empleados VALUES (7521,'SALA','VENDEDOR',7698,'1991/02/22', 1625,650,30);
INSERT INTO empleados VALUES (7566,'JIMÉNEZ','DIRECTOR',7839,'1991/04/02', 2900,NULL,20);
INSERT INTO empleados VALUES (7654,'MARTÍN','VENDEDOR',7698,'1991/09/29',1600,1020,30);
INSERT INTO empleados VALUES (7698,'NEGRO','DIRECTOR',7839,'1991/05/01',  3005,NULL,30);
INSERT INTO empleados VALUES (7782,'CEREZO','DIRECTOR',7839,'1991/06/09',2885,NULL,10);
INSERT INTO empleados VALUES (7788,'GIL','ANALISTA',7566,'1991/11/09', 3000,NULL,20);
INSERT INTO empleados VALUES (7839,'REY','PRESIDENTE',NULL,'1991/11/17',  4100,NULL,10);
INSERT INTO empleados VALUES (7844,'TOVAR','VENDEDOR',7698,'1991/09/08',1350,0,30);
INSERT INTO empleados VALUES (7876,'ALONSO','EMPLEADO',7788,'1991/09/23', 1430,NULL,20);
INSERT INTO empleados VALUES (7900,'JIMENO','EMPLEADO',7698,'1991/12/03',1335,NULL,30);
INSERT INTO empleados VALUES (7902,'FERNÁNDEZ','ANALISTA',7566,'1991/12/03', 3000,NULL,20);
INSERT INTO empleados VALUES (7934,'MUÑOZ','EMPLEADO',7782,'1992/01/23', 1690,NULL,10);
COMMIT;

Y lanzar esta clase, que compartirán los dos ejercicios:

ARCHIVO SESSIONFACTORYUTIL.JAVA

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class SessionFactoryUtil {

     private static final SessionFactory sessionFactory;
     static {
          try {
                sessionFactory= new Configuration().configure().buildSessionFactory();
          } catch (Throwable ex) {
                System.err.println("Initial SessionFactory creation failed. " + ex);
                throw new ExceptionInInitializerError(ex);
          }
     }
     public static SessionFactory getSessionFactory(){
          return sessionFactory;
     }
}

Ejercicio 1. Crea un proyecto que mapee las tablas EMPLEADOS y DEPARTAMENTOS. Al ejecutarlo, nos pedirá introducir un número de departamento. Tras pulsar el botón consultar se debe visualizar el nombre del Departamento y a continuación los datos de los empleados de dicho departamento. Debe aparecer el número de empleados que tiene. Si el departamento no existe debe visualizar un mensaje indicándolo. Puedes utilizar un JTextArea para visualizar los datos de los empleados. Ejemplo de funcionamiento:



ARCHIVO EJERCICIO1.JAVA

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import javax.swing.JTextField;

import org.hibernate.*;

import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.List;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Ejercicio1 {

      private JFrame frmDepartamentos;
      private JTextField txtPregunta;
      JLabel lblPregunta = new JLabel("Introduce N\u00BA Departamento:");
      JButton btnPregunta = new JButton("Comprobar");
      JLabel lblResultado = new JLabel("Introduce N\u00BA Departamento:");
      JTextArea txtResultado = new JTextArea();
      private SessionFactory sessionFactory;

      /**
       * Launch the application.
       */
      public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                  public void run() {
                        try {
                             Ejercicio1 window = new Ejercicio1();
                             window.frmDepartamentos.setVisible(true);
                        } catch (Exception e) {
                             e.printStackTrace();
                        }
                  }
            });
      } // Fin Main

      /**
       * Create the application.
       */
      public Ejercicio1() {
            initialize();
      } // Fin Constructor

      /**
       * Inicia la conexión con la base de datos
       */
      private void conectar(){
            sessionFactory = SessionFactoryUtil.getSessionFactory();
      }
     
      /**
       * Libera los recursos de la conexion
       */
      private void desconectar(){
            sessionFactory.close();
            sessionFactory = null;
      }
     
      /**
       * Sale de la aplicación
       */
      private void salir(){
            if(sessionFactory != null){
                  desconectar();
            }
      }
      /**
       * Cargo el contenido de las tablas
       */
      private void cargarDatos(int d){
            Iterator<Departamentos> i;
            Iterator<Empleados> iE;
            conectar();
            Session session = sessionFactory.openSession();
            Query query = session.createQuery("FROM Departamentos where dept_no = " + d);
            List<Departamentos> departamentos = query.list();
           
            if (departamentos.isEmpty()){
                  JOptionPane.showMessageDialog(null, "No existe este departamento");
            }
            else{
                 
                  i = departamentos.iterator();
                  while(i.hasNext()){
                        if (!this.lblResultado.isVisible())
                             this.lblResultado.setVisible(true);
                        this.lblResultado.setText("Nombre departamento: " + i.next().getDnombre());
                  }
                 
                  query = session.createQuery("FROM Empleados where dept_no = " + d);
                  List<Empleados> empleados = query.list();
                  this.txtResultado.setVisible(true);
                  this.txtResultado.setText("Numero de empleados: " + empleados.size() + "\n");
                  this.txtResultado.setText(txtResultado.getText() + "----------------------------------------------------\n");
                  this.txtResultado.setText(txtResultado.getText() + "APELLIDO\tOFICIO\n");
                  this.txtResultado.setText(txtResultado.getText() + "----------------------------------------------------\n");
                  iE = empleados.iterator();
                  while(iE.hasNext()){
                        this.txtResultado.setText(this.txtResultado.getText() + iE.next().toString() + "\n");
                  }
            }
            session.close();
      } // Fin cargarDatos
     
      /**
       * Initialize the contents of the frame.
       */
      private void initialize() {
            frmDepartamentos = new JFrame();
            frmDepartamentos.addWindowListener(new WindowAdapter() {
                  @Override
                  public void windowClosing(WindowEvent arg0) {
                        salir();
                  }
            });
            frmDepartamentos.setTitle("Departamentos");
            frmDepartamentos.setBounds(100, 100, 488, 427);
            frmDepartamentos.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frmDepartamentos.setLocationRelativeTo(null);
            frmDepartamentos.getContentPane().setLayout(null);
           
           
            lblPregunta.setFont(new Font("Tahoma", Font.BOLD, 14));
            lblPregunta.setBounds(10, 11, 220, 14);
            frmDepartamentos.getContentPane().add(lblPregunta);
           
            txtPregunta = new JTextField();
            txtPregunta.setHorizontalAlignment(SwingConstants.RIGHT);
            txtPregunta.setBounds(232, 10, 86, 20);
            frmDepartamentos.getContentPane().add(txtPregunta);
            txtPregunta.setColumns(10);
           
           
            btnPregunta.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent arg0) {
                        if (txtPregunta.getText().equals("")){
                             JOptionPane.showMessageDialog(null, "Debes poner un número de departamento");
                        }
                        else{
                             int x = Integer.parseInt(txtPregunta.getText());
                             cargarDatos(x);
                        }
                  }
            });
            btnPregunta.setFont(new Font("Tahoma", Font.BOLD, 14));
            btnPregunta.setBounds(335, 9, 127, 23);
            frmDepartamentos.getContentPane().add(btnPregunta);
           
           
            lblResultado.setFont(new Font("Tahoma", Font.BOLD, 12));
            lblResultado.setBounds(10, 47, 416, 14);
            lblResultado.setVisible(false);
            frmDepartamentos.getContentPane().add(lblResultado);
           
           
            txtResultado.setBounds(10, 72, 452, 305);
            txtResultado.setVisible(false);
            this.txtResultado.setEditable(false);
            frmDepartamentos.getContentPane().add(txtResultado);
      } // Fin initialize
} // Fin Ejercicio1

Ejercicio  2. Ídem del anterior pero para realizar altas, bajas y modificaciones sobre la tabla DEPARTAMENTOS. Después de dar de alta un departamento, modificarlo o borrarlo, debe visualizarse un mensaje indicando la acción realizada.


ARCHIVO EJERCICIO2.JAVA

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.*;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class Ejercicio2 {

      // Propiedades
      private JFrame frmPanelDeGestin;
      private JTextField txtLocalidad;
      private JTextField txtNombre;
      private JTextField txtDepartamento;
      private JLabel lblTitulo = new JLabel("GESTI\u00D3N DE DEPARTAMENTOS");
      private SessionFactory sessionFactory;
      private Session session;
      private Transaction tx;
      private Departamentos d = new Departamentos();

      // Métodos
      /**
       * Launch the application.
       */
      public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                  public void run() {
                        try {
                             Ejercicio2 window = new Ejercicio2();
                             window.frmPanelDeGestin.setVisible(true);
                        } catch (Exception e) {
                             e.printStackTrace();
                        }
                  }
            });
      } // Fin Main

      /**
       * Create the application.
       */
      public Ejercicio2() {
            initialize();
      } // Fin Constructor

      /**
       * Initialize the contents of the frame.
       */
      private void initialize() {
            frmPanelDeGestin = new JFrame();
            frmPanelDeGestin.setTitle("Panel de gesti\u00F3n");
            frmPanelDeGestin.setBounds(100, 100, 484, 240);
            frmPanelDeGestin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frmPanelDeGestin.setLocationRelativeTo(null);
            frmPanelDeGestin.getContentPane().setLayout(null);
           
            lblTitulo.setFont(new Font("Tahoma", Font.BOLD, 14));
            lblTitulo.setBounds(110, 11, 247, 14);
            frmPanelDeGestin.getContentPane().add(lblTitulo);
           
            JLabel lblNDepartamento = new JLabel("N\u00BA de Departamento:");
            lblNDepartamento.setFont(new Font("Tahoma", Font.BOLD, 12));
            lblNDepartamento.setBounds(20, 46, 142, 14);
            frmPanelDeGestin.getContentPane().add(lblNDepartamento);
           
            JLabel lblNombre = new JLabel("Nombre:");
            lblNombre.setFont(new Font("Tahoma", Font.BOLD, 12));
            lblNombre.setBounds(20, 86, 142, 14);
            frmPanelDeGestin.getContentPane().add(lblNombre);
           
            JLabel lblLocalidad = new JLabel("Localidad:");
            lblLocalidad.setFont(new Font("Tahoma", Font.BOLD, 12));
            lblLocalidad.setBounds(21, 125, 142, 14);
            frmPanelDeGestin.getContentPane().add(lblLocalidad);
           
            txtLocalidad = new JTextField();
            txtLocalidad.setHorizontalAlignment(SwingConstants.RIGHT);
            txtLocalidad.setBounds(183, 123, 229, 20);
            frmPanelDeGestin.getContentPane().add(txtLocalidad);
            txtLocalidad.setColumns(10);
           
            txtNombre = new JTextField();
            txtNombre.setHorizontalAlignment(SwingConstants.RIGHT);
            txtNombre.setColumns(10);
            txtNombre.setBounds(183, 84, 229, 20);
            frmPanelDeGestin.getContentPane().add(txtNombre);
           
            txtDepartamento = new JTextField();
            txtDepartamento.setHorizontalAlignment(SwingConstants.RIGHT);
            txtDepartamento.setColumns(10);
            txtDepartamento.setBounds(296, 44, 116, 20);
            frmPanelDeGestin.getContentPane().add(txtDepartamento);
           
            JButton btnAlta = new JButton("Alta");
            btnAlta.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent arg0) {
                        alta();
                  }
            });
            btnAlta.setFont(new Font("Tahoma", Font.BOLD, 12));
            btnAlta.setBounds(17, 165, 89, 23);
            frmPanelDeGestin.getContentPane().add(btnAlta);
           
            JButton btnBaja = new JButton("Baja");
            btnBaja.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent arg0) {
                        baja();
                  }
            });
            btnBaja.setFont(new Font("Tahoma", Font.BOLD, 12));
            btnBaja.setBounds(123, 166, 89, 23);
            frmPanelDeGestin.getContentPane().add(btnBaja);
           
            JButton btnModificacion = new JButton("Modificacion");
            btnModificacion.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent arg0) {
                        modificar();
                  }
            });
            btnModificacion.setFont(new Font("Tahoma", Font.BOLD, 12));
            btnModificacion.setBounds(229, 165, 116, 23);
            frmPanelDeGestin.getContentPane().add(btnModificacion);
           
            JButton btnLimpiar = new JButton("Limpiar");
            btnLimpiar.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                        limpiar();
                  }
            });
            btnLimpiar.setFont(new Font("Tahoma", Font.BOLD, 12));
            btnLimpiar.setBounds(362, 166, 89, 23);
            frmPanelDeGestin.getContentPane().add(btnLimpiar);
           
            conectar();
      } // Fin initialize
     
      /**
       * Inicia la conexión con la base de datos
       */
      private void conectar(){
            sessionFactory = SessionFactoryUtil.getSessionFactory();
      }
     
      /**
       * Libera los recursos de la conexion
       */
      private void desconectar(){
            sessionFactory.close();
            sessionFactory = null;
      }
     
      /**
       * Sale de la aplicación
       */
      private void salir(){
            if(sessionFactory != null){
                  desconectar();
            }
      }
     
      /**
       * Deja en blanco los campos de texto
       */
      private void limpiar(){
            this.txtDepartamento.setText("");
            this.txtLocalidad.setText("");
            this.txtNombre.setText("");
      } // Fin limpiar
     
      private void alta(){
            if (isVacio(txtDepartamento)){
                  JOptionPane.showMessageDialog(null, "El número de departamento no puede estar vacío");
            }
            else{
                  if (!isDepto((byte)Integer.parseInt(this.txtDepartamento.getText()))){
                        session = sessionFactory.openSession();
                        tx = session.beginTransaction();
                        d.setDeptNo((byte)Integer.parseInt(this.txtDepartamento.getText()));
                        d.setDnombre(this.txtNombre.getText());
                        d.setLoc(this.txtLocalidad.getText());
                        session.save(d);
                        tx.commit();
                        session.close();
                        JOptionPane.showMessageDialog(null, "Inserción correcta");
                  }
                  else{
                        JOptionPane.showMessageDialog(null, "El número de departamento ya existe");
                  }
            }
      } // Fin alta
     
      /**
       * Borro los campos de la tabla que coincidan con los criterios de búsqueda
       */
      private void baja(){
            // Si todos los campos están vacios muestro mensaje de error
            if (isVacio(txtDepartamento) && isVacio(this.txtLocalidad) && isVacio(this.txtNombre)){
                  JOptionPane.showMessageDialog(null, "No puedes dejar todos los campos vacíos");
            }
            else{
                  String consulta = "FROM Departamentos where ";
                  boolean banderaModificado = false;
                  if (!isVacio(this.txtDepartamento)){
                        if (banderaModificado){
                             consulta = consulta + " and dept_no = " + (byte)Integer.parseInt(this.txtDepartamento.getText());
                        }
                        else{
                             consulta = consulta + " dept_no = " + (byte)Integer.parseInt(this.txtDepartamento.getText());
                             banderaModificado = true;
                        }
                  } // Si departamento vacio
                 
                  if (!isVacio(this.txtLocalidad)){
                        if (banderaModificado){
                             consulta = consulta + " and loc = " + this.txtLocalidad.getText();
                        }
                        else{
                             consulta = consulta + " loc = " + this.txtLocalidad.getText();
                             banderaModificado = true;
                        }
                  } // Si localidad vacia
                 
                  if (!isVacio(this.txtNombre)){
                        if (banderaModificado){
                             consulta = consulta + " and dnombre = " + this.txtNombre.getText();
                        }
                        else{
                             consulta = consulta + " dnombre = " + this.txtNombre.getText();
                             banderaModificado = true;
                        }
                  } // Si nombre vacío
                 
                  session = sessionFactory.openSession();
                  Query query = session.createQuery(consulta);
                  List<Departamentos> departamentos = query.list();
                  Iterator<Departamentos> iter = departamentos.iterator();
                 
                  while(iter.hasNext()){
                        d = iter.next();
                        session.delete(d);
                  }
                 
                  JOptionPane.showMessageDialog(null, "Se han borrado " + departamentos.size() + " registros");
                 
                  session.close();
                  banderaModificado = false; // Reinicio bandera para proximas consultas
                 
            } // Fin else todos los campos vacíos
      } // Fin baja
     
      /**
       * Actualiza un registro de tabla indicando su número de departamento.
       */
      private void modificar(){
            if (isVacio(txtDepartamento)){
                  JOptionPane.showMessageDialog(null, "El número de departamento no puede estar vacío");
            }
            else{
                  if (isDepto((byte)Integer.parseInt(this.txtDepartamento.getText()))){
                        Query query;
                        int resultado; // Devuelve filas afectadas
                        session = sessionFactory.openSession();
                        if (isVacio(this.txtLocalidad) && isVacio(this.txtNombre)){
                             JOptionPane.showMessageDialog(null, "Pues no vas a cambiar ná si no pones ná pa cambiar");
                        }
                        else if (isVacio(this.txtLocalidad)){
                             query = session.createQuery("update Departamentos set dnombre = :dnombre" + " where dept_no = :dept_no");
                             query.setParameter("dnombre", this.txtNombre.getText());
                             query.setParameter("dept_no", (byte)Integer.parseInt(this.txtDepartamento.getText()));
                             resultado = query.executeUpdate();
                             JOptionPane.showMessageDialog(null, "Modificados " + resultado + " registros");
                        }
                        else if (isVacio(this.txtNombre)){
                             query = session.createQuery("update Departamentos set loc = :loc" + " where dept_no = :dept_no");
                             query.setParameter("loc", this.txtLocalidad.getText());
                             query.setParameter("dept_no", (byte)Integer.parseInt(this.txtDepartamento.getText()));
                             resultado = query.executeUpdate();
                             JOptionPane.showMessageDialog(null, "Modificados " + resultado + " registros");
                        }
                        else{
                             query = session.createQuery("update Departamentos set dnombre = :dnombre, loc = :loc" + " where dept_no = :dept_no");
                             query.setParameter("dnombre", this.txtNombre.getText());
                             query.setParameter("loc", this.txtLocalidad.getText());
                             query.setParameter("dept_no", (byte)Integer.parseInt(this.txtDepartamento.getText()));
                             resultado = query.executeUpdate();
                             JOptionPane.showMessageDialog(null, "Modificados " + resultado + " registros");
                        }
                  }
                  else{
                        JOptionPane.showMessageDialog(null, "El código no pertenece a ningún registro");
                  }
            }
      } // Fin modificar
     
     
      /**
       * Devuelve TRUE si el departamento existe y false si no
       */
      private boolean isDepto(byte b){
            session = sessionFactory.openSession();
            Query query = session.createQuery("FROM Departamentos where dept_no = " + b);
            List<Departamentos> departamentos = query.list();
            if (departamentos.isEmpty())
                  return false;
            else
                  return true;
      } // Fin isAlta
     
      /**
       * Devuelve TRUE si el textArea está vacio, y false si tiene contenido
       * @param t es JTextField a analizar
       * @return
       */
      private boolean isVacio(JTextField t){
            return t.getText().equals("");
      } // Fin isVacio
} // Fin Ejercicio2

0 comentarios:

Publicar un comentario