DAO - Data Access Object

De Aulas

Links relacionados: Banco de Dados

Base de Dados

Para o exemplo, criei a base de dados chamada dao.

 1create table funcionario (
 2	idfuncionario serial,
 3	nome varchar(50),
 4	salario numeric(7,2),
 5	primary key (idfuncionario)
 6);
 7
 8create table dependente (
 9	idfuncionario integer references funcionario,
10	iddependente serial,
11	nome varchar(50),
12	idade integer,
13	primary key (iddependente)
14);

Classe de Conexão

 1import java.sql.Connection;
 2import java.sql.DriverManager;
 3import java.sql.SQLException;
 4
 5public class DatabaseConnection {
 6	static private Connection connection = null;
 7	static private String url = "";
 8	static private String username = "";
 9	static private String password = "";
10	static private String dbdriver = "";
11
12	static public void setConfig(String iurl, String uname, String pass,
13			String dbdrv) {
14		url = iurl;
15		username = uname;
16		password = pass;
17		dbdriver = dbdrv;
18	}
19
20	static public Connection getConnection() {
21		if (connection == null) {
22			try {
23				Class.forName(dbdriver);
24				connection = DriverManager.getConnection(url, username,
25						password);
26			} catch (SQLException e1) {
27				e1.printStackTrace();
28			} catch (ClassNotFoundException e) {
29				e.printStackTrace();
30			}
31		}
32		return connection;
33	}
34}

Objetos de Transferência =

Funcionario

 1public class Funcionario {
 2	private int idFuncionario;
 3	private String nome;
 4	private float salario;
 5
 6	public int getIdFuncionario() {
 7		return idFuncionario;
 8	}
 9
10	public String getNome() {
11		return nome;
12	}
13
14	public float getSalario() {
15		return salario;
16	}
17
18	public void setIdFuncionario(int id) {
19		idFuncionario = id;
20	}
21
22	public void setNome(String n) {
23		nome = n;
24	}
25
26	public void setSalario(float s) {
27		salario = s;
28	}
29}

Dependente

 1public class Dependente {
 2	private int idFuncionario;
 3	private int idDependente;
 4	private String nome;
 5	private int idade;
 6
 7	public int getIdFuncionario() {
 8		return idFuncionario;
 9	}
10
11	public int getIdDependente() {
12		return idDependente;
13	}
14
15	public String getNome() {
16		return nome;
17	}
18
19	public int getIdade() {
20		return idade;
21	}
22
23	public void setIdFuncionario(int id) {
24		idFuncionario = id;
25	}
26
27	public void setIdDependente(int id) {
28		idDependente = id;
29	}
30
31	public void setNome(String n) {
32		nome = n;
33	}
34
35	public void setIdade(int i) {
36		idade = i;
37	}
38}

Objetos de Acesso

Funcionario DAO

  1import java.sql.Connection;
  2import java.sql.ResultSet;
  3import java.sql.SQLException;
  4import java.sql.Statement;
  5import java.util.Vector;
  6
  7public class FuncionarioDAO {
  8	private int Position;
  9	private Vector<Funcionario> funcionarioList;
 10
 11	public FuncionarioDAO() {
 12		Position = 0;
 13		funcionarioList = new Vector<Funcionario>();
 14	}
 15
 16	public void load(String filter) {
 17		try {
 18			Connection conn = DatabaseConnection.getConnection();
 19			Statement stmt = conn.createStatement();
 20
 21			String query = "select * from funcionario";
 22			if (filter.length() > 0) {
 23				query += " where " + filter;
 24			}
 25			System.out.println("QUERY: " + query);
 26			ResultSet rs = stmt.executeQuery(query);
 27			while (rs.next()) {
 28				Funcionario func = new Funcionario();
 29				func.setIdFuncionario(rs.getInt("idfuncionario"));
 30				func.setNome(rs.getString("nome"));
 31				func.setSalario(rs.getFloat("salario"));
 32				funcionarioList.add(func);
 33			}
 34			stmt.close();
 35		} catch (SQLException e) {
 36			e.printStackTrace();
 37		}
 38	}
 39
 40	public void insert(Funcionario func) {
 41		try {
 42			Connection conn = DatabaseConnection.getConnection();
 43			Statement stmt = conn.createStatement();
 44
 45			String query = "insert into funcionario (idfuncionario, nome, salario) "
 46					+ "values ("
 47					+ func.getIdFuncionario()
 48					+ ",'"
 49					+ func.getNome() + "', " + func.getSalario() + ")";
 50			System.out.println("QUERY: " + query);
 51			stmt.executeUpdate(query);
 52			stmt.close();
 53		} catch (SQLException e) {
 54			e.printStackTrace();
 55		}
 56		this.clear();
 57	}
 58
 59	public void update(Funcionario func) {
 60		try {
 61			Connection conn = DatabaseConnection.getConnection();
 62			Statement stmt = conn.createStatement();
 63
 64			String query = "update funcionario set " + "nome = '"
 65					+ func.getNome() + "', " + "salario = " + func.getSalario()
 66					+ " " + "where idfuncionario = " + func.getIdFuncionario();
 67			System.out.println("QUERY: " + query);
 68			stmt.executeUpdate(query);
 69			stmt.close();
 70		} catch (SQLException e) {
 71			e.printStackTrace();
 72		}
 73		this.clear();
 74	}
 75
 76	public void delete(int func) {
 77		try {
 78			Connection conn = DatabaseConnection.getConnection();
 79			Statement stmt = conn.createStatement();
 80			String query = "delete from dependente where idFuncionario = "
 81					+ func;
 82			System.out.println("QUERY: " + query);
 83			stmt.executeUpdate(query);
 84			query = "delete from funcionario where idFuncionario = " + func;
 85			System.out.println("QUERY: " + query);
 86			stmt.executeUpdate(query);
 87			stmt.close();
 88		} catch (SQLException e) {
 89			e.printStackTrace();
 90		}
 91		this.clear();
 92	}
 93
 94	public void clear() {
 95		Position = 0;
 96		funcionarioList.clear();
 97	}
 98
 99	public void reset() {
100		Position = 0;
101	}
102
103	public int size() {
104		return funcionarioList.size();
105	}
106
107	public Funcionario next() {
108		Funcionario func = null;
109		if (Position < funcionarioList.size()) {
110			func = funcionarioList.get(Position);
111			Position++;
112		}
113		return func;
114	}
115}

Dependente DAO

  1import java.sql.Connection;
  2import java.sql.ResultSet;
  3import java.sql.SQLException;
  4import java.sql.Statement;
  5import java.util.Vector;
  6
  7public class DependenteDAO {
  8	private int Position;
  9	private Vector<Dependente> dependenteList;
 10
 11	public DependenteDAO() {
 12		Position = 0;
 13		dependenteList = new Vector<Dependente>();
 14	}
 15
 16	public void load(int func) {
 17		try {
 18			Connection conn = DatabaseConnection.getConnection();
 19			Statement stmt = conn.createStatement();
 20
 21			String query = "select * from dependente where idFuncionario = "
 22					+ func;
 23			System.out.println("QUERY: " + query);
 24			ResultSet rs = stmt.executeQuery(query);
 25			while (rs.next()) {
 26				Dependente dep = new Dependente();
 27				dep.setIdFuncionario(func);
 28				dep.setIdDependente(rs.getInt("iddependente"));
 29				dep.setNome(rs.getString("nome"));
 30				dep.setIdade(rs.getInt("idade"));
 31				dependenteList.add(dep);
 32			}
 33			stmt.close();
 34		} catch (SQLException e) {
 35			e.printStackTrace();
 36		}
 37	}
 38
 39	public void insert(Dependente dep) {
 40		try {
 41			Connection conn = DatabaseConnection.getConnection();
 42			Statement stmt = conn.createStatement();
 43
 44			String query = "insert into dependente (idfuncionario, nome, idade) "
 45					+ "values ("
 46					+ dep.getIdFuncionario()
 47					+ ", '"
 48					+ dep.getNome() + "', " + dep.getIdade() + ")";
 49			System.out.println("QUERY: " + query);
 50			stmt.executeUpdate(query);
 51			stmt.close();
 52		} catch (SQLException e) {
 53			e.printStackTrace();
 54		}
 55		this.clear();
 56	}
 57
 58	public void update(Dependente dep) {
 59		try {
 60			Connection conn = DatabaseConnection.getConnection();
 61			Statement stmt = conn.createStatement();
 62
 63			String query = "update dependente set " + "nome = '"
 64					+ dep.getNome() + "', " + "idade = " + dep.getIdade() + " "
 65					+ "where idfuncionario = " + dep.getIdFuncionario() + " "
 66					+ "and iddependente = " + dep.getIdDependente();
 67			System.out.println("QUERY: " + query);
 68			stmt.executeUpdate(query);
 69			stmt.close();
 70		} catch (SQLException e) {
 71			e.printStackTrace();
 72		}
 73		this.clear();
 74	}
 75
 76	public void delete(int dep) {
 77		try {
 78			Connection conn = DatabaseConnection.getConnection();
 79			Statement stmt = conn.createStatement();
 80			String query = "delete from dependente where idDependente = " + dep;
 81			System.out.println("QUERY: " + query);
 82			stmt.executeUpdate(query);
 83			stmt.close();
 84		} catch (SQLException e) {
 85			e.printStackTrace();
 86		}
 87		this.clear();
 88	}
 89
 90	public void clear() {
 91		Position = 0;
 92		dependenteList.clear();
 93	}
 94
 95	public void reset() {
 96		Position = 0;
 97	}
 98
 99	public int size() {
100		return dependenteList.size();
101	}
102
103	public Dependente next() {
104		Dependente dep = null;
105		if (Position < dependenteList.size()) {
106			dep = dependenteList.get(Position);
107			Position++;
108		}
109		return dep;
110	}
111}

Aplicação

  1import java.util.Scanner;
  2
  3public class Main {
  4	private FuncionarioDAO funcionarios;
  5	private DependenteDAO dependentes;
  6	Scanner entrada;
  7
  8	public Main() {
  9		DatabaseConnection.setConfig("jdbc:postgresql://localhost/dao",
 10				"usuario", "****", "org.postgresql.Driver");
 11		funcionarios = new FuncionarioDAO();
 12		dependentes = new DependenteDAO();
 13		entrada = new Scanner(System.in);
 14	}
 15
 16	public void showMenu() {
 17		System.out.println("Comandos Funcionarios:");
 18		System.out.println("\t lf : listar funcionario");
 19		System.out.println("\t if : inserir novo funcionario");
 20		System.out.println("\t df : deletar funcionario");
 21		System.out.println("\t af : alterar dados de um funcionario");
 22		System.out.println("Comandos Dependentes:");
 23		System.out.println("\t ld : listar dependentes de um funcionario");
 24		System.out.println("\t id : inserir dependente para um funcionario");
 25		System.out.println("\t dd : deletar dependente");
 26		System.out.println("\t ad : alterar dados de um dependente");
 27		System.out.println("sair : Sai do programa");
 28		System.out.println("");
 29		System.out.print("Comando: ");
 30	}
 31
 32	public void menu() {
 33		String choice = "";
 34		while (!choice.contains("sair")) {
 35			showMenu();
 36			choice = entrada.nextLine();
 37			if (choice.contains("lf"))
 38				listarFuncionarios();
 39			else if (choice.contains("if"))
 40				inserirFuncionario();
 41			else if (choice.contains("df"))
 42				deletarFuncionario();
 43			else if (choice.contains("af"))
 44				alterarFuncionario();
 45			else if (choice.contains("ld"))
 46				listarDependentes();
 47			else if (choice.contains("id"))
 48				inserirDependente();
 49			else if (choice.contains("dd"))
 50				deletarDependente();
 51			else if (choice.contains("ad"))
 52				alterarDependente();
 53		}
 54	}
 55
 56	public void listarFuncionarios() {
 57		System.out.print("Filtro: ");
 58		funcionarios.load(entrada.nextLine());
 59		Funcionario f;
 60		while ((f = funcionarios.next()) != null) {
 61			System.out.println("" + f.getIdFuncionario() + " - " + f.getNome()
 62					+ " - " + f.getSalario());
 63		}
 64	}
 65
 66	public void listarDependentes() {
 67		System.out.print("Codigo do Funcionario : ");
 68		dependentes.load(Integer.valueOf(entrada.nextLine()));
 69		Dependente d;
 70		while ((d = dependentes.next()) != null) {
 71			System.out.println("" + d.getIdDependente() + " - " + d.getNome()
 72					+ " - " + d.getIdade());
 73		}
 74	}
 75
 76	public void deletarFuncionario() {
 77		System.out.print("Codigo do Funcionario a deletar : ");
 78		funcionarios.delete(Integer.valueOf(entrada.nextLine()));
 79	}
 80
 81	public void deletarDependente() {
 82		System.out.print("Codigo do Dependente a deletar : ");
 83		dependentes.delete(Integer.valueOf(entrada.nextLine()));
 84	}
 85
 86	public Funcionario lerFuncionario() {
 87		Funcionario f = new Funcionario();
 88		System.out.print("idFuncionario: ");
 89		f.setIdFuncionario(Integer.valueOf(entrada.nextLine()));
 90		System.out.print("Nome: ");
 91		f.setNome(entrada.nextLine());
 92		System.out.print("Salario: ");
 93		f.setSalario(Float.valueOf(entrada.nextLine()));
 94		return f;
 95	}
 96
 97	public void inserirFuncionario() {
 98		System.out.println("Inserindo novo Funcionario");
 99		funcionarios.insert(this.lerFuncionario());
100	}
101
102	public void alterarFuncionario() {
103		System.out.println("Alterando Funcionario");
104		funcionarios.update(this.lerFuncionario());
105	}
106
107	public Dependente lerDependente() {
108		Dependente d = new Dependente();
109		System.out.print("idFuncionario: ");
110		d.setIdFuncionario(Integer.valueOf(entrada.nextLine()));
111		System.out.print("Nome: ");
112		d.setNome(entrada.nextLine());
113		System.out.print("Idade: ");
114		d.setIdade(Integer.valueOf(entrada.nextLine()));
115		return d;
116	}
117
118	public void inserirDependente() {
119		System.out.println("Inserindo novo Dependente");
120		dependentes.insert(this.lerDependente());
121	}
122
123	public void alterarDependente() {
124		System.out.println("Alterando Dependente");
125		System.out.print("idDependente: ");
126		int id = Integer.valueOf(entrada.nextLine());
127		Dependente d = this.lerDependente();
128		d.setIdDependente(id);
129		dependentes.update(d);
130	}
131
132	public static void main(String[] arguments) {
133		Main m = new Main();
134		m.menu();
135	}
136}