terça-feira, 28 de setembro de 2010

Aula 7 - 28.09.2010 - Classes Java

Menu.java

package br.edu.metodista.acesso.menu;

public class Menu {

   private Long id;
   private String nome;

   public Long getId() { return id; }
   public void setId(Long id) { this.id = id; }

   public String getNome() { return nome; }
   public void setNome(String nome) {       this.nome = nome; }

   @Override
   public boolean equals(Object obj) {
      if (obj == null) {
         return false;
      }
      if (getClass() != obj.getClass()) {
         return false;
      }
      final Menu other = (Menu) obj;
      if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
         return false;
      }
      return true;
   }

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

   @Override
   public String toString() {
      return nome;
   }
}


MenuDAO.java

package br.edu.metodista.acesso.menu;

import java.sql.*;
import java.util.*;
import br.edu.metodista.ipa.bd.*;

public class MenuDAO {

   public int salvar(Menu menu) throws Exception {
      if (existe(menu))
         return alterar(menu);
      else
         return incluir(menu);
   }

   public int incluir(Menu menu) throws Exception {
      Connection conn = BD.getConnection();
      PreparedStatement stmt = conn.prepareStatement(INCLUIR_SQL);
      try {
         stmt.setLong(1, BD.getProximoId(TABELA));
         stmt.setString(2, menu.getNome());
         return stmt.executeUpdate();
      } finally {
         stmt.close();
         conn.close();
      }
   }

   public int alterar(Menu menu) throws Exception {
      Connection conn = BD.getConnection();
      PreparedStatement stmt = conn.prepareStatement(ALTERAR_SQL);
      try {
         stmt.setLong(1, menu.getId());
         stmt.setString(2, menu.getNome());
         stmt.setLong(3, menu.getId());
         return stmt.executeUpdate();
      } finally {
         stmt.close();
         conn.close();
      }
   }

   public int excluir(Menu menu) throws Exception {
      Connection conn = BD.getConnection();
      PreparedStatement stmt = conn.prepareStatement(EXCLUIR_SQL);
      try {
         stmt.setLong(1, menu.getId());
         return stmt.executeUpdate();
      } finally {
         stmt.close();
         conn.close();
      }
   }

   public boolean existe(Menu menu) throws Exception {
      if (menu.getId() == null)
         return false;
      
      Connection conn = BD.getConnection();
      PreparedStatement stmt = conn.prepareStatement(EXISTE_SQL);
      try {
         stmt.setLong(1, menu.getId());
         RecordSet rs = new RecordSet(stmt.executeQuery());
         if (rs.next())
            return true;
         return false;
      } finally {
         stmt.close();
         conn.close();
      }
   }

   public boolean carregar(Menu menu) throws Exception {
      Connection conn = BD.getConnection();
      PreparedStatement stmt = conn.prepareStatement(CARREGAR_SQL);
      try {
         stmt.setLong(1, menu.getId());
         RecordSet rs = new RecordSet(stmt.executeQuery());
         if (rs.next()) {
            menu.setNome(rs.getString("nome"));
            return true;
         }
         return false;
      } finally {
         stmt.close();
         conn.close();
      }
   }

   public ArrayList listar() throws Exception {
      ArrayList lista = new ArrayList();
      Connection conn = BD.getConnection();
      PreparedStatement stmt = conn.prepareStatement(LISTAR_SQL);
      try {
         RecordSet rs = new RecordSet(stmt.executeQuery());
         while (rs.next()) {
            Menu menu = new Menu();
            menu.setId(rs.getLong("id"));
            menu.setNome(rs.getString("nome"));
         }
         return lista;
      } finally {
         stmt.close();
         conn.close();
      }
   }

   private static final String TABELA = "tbl_menu";
   private static final String INCLUIR_SQL  = "INSERT INTO " + TABELA + " (id, nome) VALUES (?,?)";
   private static final String ALTERAR_SQL  = "UPDATE " + TABELA + " SET id=?, nome=? WHERE id=?";
   private static final String EXCLUIR_SQL  = "DELETE FROM " + TABELA + " WHERE id=?";
   private static final String CARREGAR_SQL = "SELECT * FROM " + TABELA + " WHERE id=?";
   private static final String EXISTE_SQL   = "SELECT id FROM " + TABELA + " WHERE id=?";
   private static final String LISTAR_SQL   = "SELECT * FROM " + TABELA + " ";

   public static void main(String[] args) throws Exception {
      Menu s = null;

      s = new Menu();
      s.setNome("Países");
      new MenuDAO().salvar(s);

      s = new Menu();
      s.setNome("Estados");
      new MenuDAO().salvar(s);

      s = new Menu();
      s.setNome("Cidades");
      new MenuDAO().salvar(s);
   }
}

Aula 7 - 28.09.2010

Esta semana daremos continuidade à criação da estrutura que servirá de base comum para todos os trabalhos que serão entregues na disciplina.

Para tanto, o seguinte modelo será utilizado para a criação das classes java para controle de acesso ao sistema.


Importante notar que para completar a arquitetura, para cada classe de negócio deverá ser avaliada a criação de uma classe de acesso aos dados (DAO), além da interface gráfica com o usuário.

Abaixo segue uma proposta básica de script SQL para mapear a estrutura OO do diagrama acima:

CREATE TABLE tbl_menu (
 id INTEGER NOT NULL PRIMARY KEY,
 nome VARCHAR(100) NOT NULL
);

CREATE TABLE tbl_grupo (
 id INTEGER NOT NULL PRIMARY KEY,
 cod VARCHAR(12) NOT NULL UNIQUE,
 nome VARCHAR(60) NOT NULL
);

CREATE TABLE tbl_permissao (
 id INTEGER NOT NULL PRIMARY KEY,
 id_grupo INTEGER NOT NULL REFERENCES tbl_grupo(id),
 id_menu INTEGER NOT NULL REFERENCES tbl_menu(id)
);

CREATE TABLE tbl_usuario (
 id INTEGER NOT NULL PRIMARY KEY,
 login VARCHAR(20) NOT NULL UNIQUE,
 senha VARCHAR(20) NOT NULL,
 cpf VARCHAR(20),
 id_grupo INTEGER NOT NULL REFERENCES tbl_grupo(id)
);

terça-feira, 21 de setembro de 2010

Aula 6 - 21.09.2010

Dica do desafio de hoje:

TODO: recolocar o código do ResultSetMetadata.

Aproveitando o post, segue abaixo o código da classe RSet:

package br.edu.metodista.ipa.bd;

import java.sql.*;
import com.sun.rowset.CachedRowSetImpl;

public class RecordSet extends CachedRowSetImpl {

    public RecordSet(ResultSet rs) throws SQLException {
        super();
        try {
            populate(rs);
        } finally {
            rs.close();
        }
    }
}

terça-feira, 14 de setembro de 2010

Aula 5 - 14.09.2010

Hoje será visto como o Java se comunica com um Banco de Dados Relacional.

Importante ressaltar que para um uso mais efetivo de bancos de dados relacionais (Oracle, Postgresql, MySQL, DB2, SQLServer, etc) a teoria relacional deve ser compreendida da melhor forma possível. Abaixo, alguns links para auxiliar neste percurso:
Conceito como "Chave Primária", "Chave Estrangeira", "Integridade Relacional" devem ser compreendidas para se trabalhar bem com um banco de dados relacional.

Para o Java, é relativamente simples realizar uma conexão a um banco de dados relacional para posterior envio de comandos e recebimento de retornos. Para tanto, uma classe como a exposta abaixo é suficiente:

package br.edu.metodista.ipa.bd;

import java.sql.*;

public class BD {

    private static final String url =
        "jdbc:derby://localhost:1527/ipa;create=true;user=admin;password=123123";

    public static Connection getConnection() throws Exception {
        return DriverManager.getConnection(url);
    }

    public static int execute(String sql) throws Exception {
        Connection conn = BD.getConnection();
        Statement stmt = conn.createStatement();
        try {
            return stmt.executeUpdate(sql);
        } finally {
            stmt.close();
            conn.close();
        }
    }

    public static RecordSet executeQuery(String sql) throws Exception {
        Connection conn = BD.getConnection();
        Statement stmt = conn.createStatement();
        try {
            ResultSet rs = stmt.executeQuery(sql);
            RecordSet rset = new RecordSet(rs);
            return rset;
        } finally {
            stmt.close();
            conn.close();
        }
    }

    public static Long getProximoId(String tabela) throws Exception {
        String sql = "SELECT MAX(id)+1 as ID FROM " + tabela;
        RecordSet rs = executeQuery(sql);
        if (rs.next())
            return rs.getLong(1);
        return 0L;
    }


    public static void main(String[] args) throws Exception {
      System.out.println(getConnection());
   }
}