You are on page 1of 11

JOSIEL S.

MOURA
MANIPULAO DE BANCO DE DADOS UTILIZANDO INTERFACE GRFICA
ORIENTADO A PROJETO: CONTROLE DE ESTOQUE

JOSIEL S. MOURA

MANIPULAO DE BANCO DE DADOS UTILIZANDO INTERFACE GRFICA

ORIENTADO A PROJETO: CONTROLE DE ESTOQUE


Sumrio
INTRODUO
3
PADRO DAO
4
ESTUDO DE CASO 6
Banco de Dados 6
Entidade
7
Fornecedor
7
Produto 8
Movimento
9
Dao
11
Conexo 11
Fornecedor
12
Produto 13
Movimento
15
Formulrios
17
Principal
17
Fornecedor
18
Produto 24
Entrada 30
Busca de produtos
32
Sada 35
REFENRNCIAS BIBLIOGRFICAS

38

INTRODUO
A ideia de padres foi apresentada por Christopher Alexander em 1977 no cont
exto de Arquitetura (de prdios e cidades).
Cada padro descreve um problema que ocorre repetidamente, de novo e de novo
, em nosso ambiente, e ento descreve a parte central da soluo para aquele problema
de uma forma que voc pode usar esta soluo um milho de vezes, sem nunca implement-la
duas vezes da mesma forma.

Um padro de projeto uma espcie de gabarito para como resolver um problema, o


u melhor dizendo, uma soluo elegante na resoluo de problemas.
PADRO DAO

A maioria das aplicaes empresariais usa normalmente sistemas de gerenciament


o de bancos de dados relacional (RDBMS, relational database management system) c
omo armazenamento persistente. Entretanto, estamos trabalhando em Java, que Orie
ntado a Objeto.
Misturar a lgica de persistncia com a lgica de aplicao cria uma dependncia dire
a entre a implementao da aplicao e do armazenamento persistente. Tal dependncia de cd
go nos componentes torna difcil e maante migrar a aplicao de um tipo de fonte de dad
os para outro.
Quando as fontes de dados so alteradas, os componentes devem ser modificad
os para tratar o novo tipo de fonte de dados.
Use um Data Access Object (DAO) para abstrair e encapsular todo acesso ao
armazenamento persistente. O DAO gerencia a conexo com a fonte de dados para obte
r e armazenar dados.
O DAO funciona como um tradutor dos mundos. O DAO deve saber buscar os dad
os do banco relacional e converter em objetos para ser usado pela aplicao. Semelha
ntemente, deve saber como pegar os objetos, converter em instrues SQL e mandar par
a o banco de dados relacional. assim que um DAO trabalha.
O principal objetivo de um DAO encapsular o acesso e a manipulao de dados em
uma camada separada.
ESTUDO DE CASO
Banco de Dados
Abaixo temos o diagrama de Entidade-Relacionamento para o sistema de contr
ole de estoque que ter foco no cadastro de produtos e na movimentao (entrada e sada)
desses produtos.
Figura 1: Diagrama de entidade e relacionamento
Entidade
A entidade a representao da tabela do banco de dados em nosso aplicativo. De
ve ser criados os mtodos get s e set s para implementar o encapsulamento de nosso cdig
o.
Fornecedor

Listagem 1: Classe Fornecedor.java

Produto

Movimento

4 private double quantidade;


5 private String data;
6 private Produto produto; 7
8 public int getId() {
9 return id;
10
}
11
12 public void setId(int id) {
13 this.id = id; 14
}
15
16 public String getTipo() {
17 return tipo; 18
}
19
20 public void setTipo(String tipo) {
21 this.tipo = tipo; 22 }
23
24 public double getQuantidade() {
25 return quantidade; 26
}
27
28 public void setQuantidade(double quantidade) {
29 this.quantidade = quantidade; 30
}
31
32 public String getData() {
33 return data; 34
}
35
36 public void setData(String data) {
37 this.data = data; 38 }
39
40 public Produto getProduto() {
41 return produto; 42 }
43

Dao

Primeiramente precisamos de uma classe que estabelea


a conexo com o banco de dados:
Conexo
Listagem 2: Classe Conexao.java
Vamos criar uma classe AlunoDAO que possui os mtodos para manipular (salv
ar, atualizar, apagar e consultar) um objeto Aluno.
Fornecedor

Listagem 3: Classe FornecedorDao.java

Produto

6 FornecedorDao fornecedorDao = new FornecedorDao();


7 String sql; 8
9 public ProdutoDao() throws Exception {
10 conectar(); 11
}
12
13 public Produto getProduto(int id)throws Exception{
14 sql="SELECT * FROM produto WHERE idProduto="+id;
15 rs = stm.executeQuery(sql);
16 if(rs.next()){
17 p = new Produto();
18 p.setId( rs.getInt(1));
19 p.setCodigo( rs.getString(2));
20 p.setNome(rs.getString(3));
21 p.setEstoque(rs.getDouble(4));
22 p.setValor(rs.getDouble(5));
23 p.setFornecedor(fornecedorDao.getFornecedor(rs.getInt(6))); 24
}
25
return p; 26
}
27
28 public List<Produto> pesquisar(String nome)throws Exception{
29 List<Produto> produtos = new LinkedList();
30 sql="SELECT * FROM produto WHERE nome_produto LIKE '"+nome+"%' ORDER BY nome_
produto";
31 rs = stm.executeQuery(sql);
32 while(rs.next()){
33 p = new Produto();
34 p.setId( rs.getInt(1));
35 p.setCodigo( rs.getString(2));
36 p.setNome(rs.getString(3));
37 p.setEstoque(rs.getDouble(4));
38 p.setValor(rs.getDouble(5));
39 p.setFornecedor(fornecedorDao.getFornecedor(rs.getInt(6)));
40 produtos.add(p); 41 }
42
return produtos; 43
}
44
45 public void cadastrar(Produto p)throws Exception{
46 sql="INSERT INTO produto(codigo,nome_produto,estoque,valor,fornecedor_idForne
cedor)"
47
+" values('"+p.getCodigo()+"','"+p.getNome()+"', 0,"+p.getValor()+","+p.
getFornecedor().getId()+")";
48
stm.executeUpdate(sql); 49
}
50
51 public void alterar(Produto p)throws Exception{
52 sql="UPDATE produto SET codigo='"+p.getCodigo()+"', nome_produto='"+p.getNome
()+"',"
53
+ " valor="+p.getValor()+", fornecedor_idFornecedor="+p.getFornecedor().
getId()
54
+ " WHERE idProduto="+p.getId();

55
57
58
59
60
62

stm.executeUpdate(sql); 56

public void excluir(int id)throws Exception{


sql="DELETE FROM produto WHERE idProduto="+id;
stm.executeUpdate(sql); 61 }
}

Movimento

movimento(tipo,quantidade,data,produto_idProduto)"
13
+ "VALUES('" + m.getTipo() + "'," + m.getQuantidade() + ",'"
+ m.getData()
14
+ "'," + m.getProduto().getId() + ")";
15 stm.executeUpdate(sql);
16 return true; 17
}
18
return false; 19
}
20
21 private boolean atualizarEstoque(Movimento m) throws Exception {
22 ProdutoDao produtoDao = new ProdutoDao();
23 double estoque = produtoDao.getProduto(m.getProduto().getId()).getEstoque();
24 if (m.getTipo().equals("Entrada")) {
25 estoque += m.getQuantidade();
26 } else {
27 if (estoque > m.getQuantidade()) {
28 estoque -= m.getQuantidade();
29 } else {
30 return false; 31
}
32
}
33 sql = "UPDATE produto SET estoque=" + estoque + " WHERE idProduto=" + m.getPr
oduto().getId();
34 stm.executeUpdate(sql);
35 return true; 36
}
37 }
Formulrios Principal

Abaixo temos os eventos para os botes


121 try
evt)
jbFornecedorActionPerformed(java.awt.event.ActionEvent
void
private
120
{ {
122 new FormularioFornecedor().show();
123 } catch (Exception ex) {
124 JOptionPane.showMessageDialog(null, ex);
125
}
126
128
129
130
131
132
133
136
137
138
139
140
141
private
144
evt)
try
145
new
146
147
JOptionPane.showMessageDialog(null,
}148
149
150
27catch
34
35
42
43
FormularioProduto().show();
{FormularioEntrada().show();
FormularioSaida().show();
{ (Exception
void jbSaidaActionPerformed(java.awt.event.ActionEvent
jbProdutoActionPerformed(java.awt.event.ActionEvent
jbEntradaActionPerformed(java.awt.event.ActionEvent
ex) {
ex);
Figura 2: Formulrio principal

Fornecedor

10
12
13
14
16
18
19
20
21
23
24
26
27
29
30
31
32
33
34
36
37
38
39
41
42
43
45
46
47
48
49

* and open the template in the editor. 11 */


/**
*
* @author Josiel 15 */
public class FormularioFornecedor extends javax.swing.JFrame { 17
private Fornecedor fornecedor = new Fornecedor();
private List<Fornecedor> fornecedores = new LinkedList<>();
private FornecedorDao fornecedorDao = new FornecedorDao();
int posicao; 22
/**
* Creates new form FormularioFornecedor 25
*/
public FormularioFornecedor() throws Exception{
initComponents(); 28 }
private void limparCampos() {
tfId.setText(null);
tfNome.setText(null);
tfTelefone.setText(null);
tfCnpj.setText(null); 35
}
private void getFornecedor() {
if (!tfId.getText().equals("")) {
fornecedor.setId(Integer.parseInt(tfId.getText())); 40
fornecedor.setNome(tfNome.getText());
fornecedor.setTelefone(tfTelefone.getText());
fornecedor.setCnpj(tfCnpj.getText()); 44
}

private void setFornecedor(Fornecedor f) {


tfId.setText(String.valueOf(f.getId()));
tfNome.setText(f.getNome());
tfTelefone.setText(f.getTelefone());

50 tfCnpj.setText(f.getCnpj()); 51
}
52
53
//Cdigo omitido 249
250 private void
btCadastrarActionPerformed(java.awt.event.ActionEvent evt) {
251 try {
252 getFornecedor();
253 fornecedorDao.cadastrar(fornecedor);
254 JOptionPane.showMessageDialog(null, "Cadastrado com sucesso!");
255 limparCampos();
256 } catch (Exception ex) {
257 JOptionPane.showMessageDialog(null, ex);
258
}
259
} 260
261 private void btFecharActionPerformed(java.awt.event.ActionEvent evt) {
262 dispose();
263
} 264
265 private void
btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {
266 try {

267
268
269
270
271
272
273
275
276
277
278
279

fornecedores = fornecedorDao.pesquisar(tfNome.getText());
posicao = 0;
setFornecedor(fornecedores.get(posicao));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
} 274
private void btProximoActionPerformed(java.awt.event.ActionEvent evt) {
if (posicao < fornecedores.size() - 1) {
posicao++;
setFornecedor(fornecedores.get(posicao));
}

280
282
if
283
286
285
posicao--;
284
289
290
292
291
294
posicao
295
297
setFornecedor(fornecedores.get(posicao));
296
299
300
303
fornecedorDao.alterar(fornecedor);
302
301
305
limparCampos();
304
306
}307
private
310
evt)
try
311
JOptionPane.showMessageDialog(null,
314
fornecedorDao.excluir(fornecedor.getId());
313
getFornecedor();
312
3209
81catch
87
88
93
98
08
(posicao
{{ void
= fornecedores.size()
(Exception
0;>btExcluirActionPerformed(java.awt.event.ActionEvent
btAnteriorActionPerformed(java.awt.event.ActionEvent
btPrimeiroActionPerformed(java.awt.event.ActionEvent
btUltimoActionPerformed(java.awt.event.ActionEvent
btAlterarActionPerformed(java.awt.event.ActionEvent
0) { ex) {
- 1; "Excluido
"Alterado com sucesso!");
ex);
315Variables
sucesso!");
316
317
318
319
321
320
evt)
322
323
325
324
352
351
353
354
355
356
357
358
359
360
361
362
//
363
btPrimeiro;
371
btPesquisar;
370
btNovo;
369
btFechar;
368
btExcluir;
367
btCadastrar;
366
btAnterior;
365
btAlterar;
364
javax.swing.JLabel
375
jButton10;
374
btUltimo;
373
javax.swing.JButton
372
jLabel1;
377
private
376
{ }});
private
limparCampos();
//Cdigo
/*
java.awt.EventQueue.invokeLater(new
public
try
new
JOptionPane.showMessageDialog(null,
jLabel2;
catch
Create
{btProximo;
FormularioFornecedor().setVisible(true);
declaration
void
void
(Exception
omitido
and
jLabel3;
javax.swing.JLabel
run()
btNovoActionPerformed(java.awt.event.ActionEvent
display
-{ex)
do the
not
{ modify
formjavax.swing.JLabel
*/ ex);
Runnable() {
378
379
380
381
382
private private privatejavax.swing.JTextField
383
javax.swing.JTextField
jLabel4;
javax.swing.JLabel
private private
javax.swing.JTextField javax.swing
// End
tfTelefone;
tfNome;
tfId;
tfCnpj;
.JTextField
384
} of variables declaration
Produto

9 * To change this template, choose Tools | Templates 10 * and open the templ
ate in the editor.
11 */
12 /**
13 *
14 * @author Josiel 15 */
16 public class FormularioProduto extends javax.swing.JFrame { 17
18 private Produto produto = new Produto();
19 private List<Produto> produtos = new LinkedList<>();
20 private ProdutoDao produtoDao = new ProdutoDao();
21 private List<Fornecedor> fornecedores = new LinkedList<>();
22 private FornecedorDao fornecedorDao = new FornecedorDao();
23 int posicao; 24
25
/**
26
* Creates new form FormularioFornecedor 27
*/
28 public FormularioProduto() throws Exception{
29 initComponents();
30 listarFornecedores(); 31
}
32
33 private void listarFornecedores() throws Exception {
34 fornecedores = fornecedorDao.pesquisar("");
35 cbFornecedor.addItem("Selecione um Fornecedor");
36 for (int i = 0; i < fornecedores.size(); i++) {
37 cbFornecedor.addItem(fornecedores.get(i).getNome()); 38
}

39
40
41
42
43
44
45
46
48

}
private void limparCampos() {
tfId.setText(null);
tfCodigo.setText(null);
tfNome.setText(null);
tfValor.setText(null);
cbFornecedor.setSelectedIndex(0); 47 }

49
50
51
52
53
54
55
56
57
cbFornecedor.getSelectedItem().toString()).get(0));
58
60
61
62
63
64
65
66
281
280
btCadastrarActionPerformed(java.awt.event.ActionEvent
282
283
284
285
286
sucesso!");
287
288
289
290
292
291
evt)
293
294
void
private
296
295
59 { }dispose();
67
if
produto.setId(Integer.parseInt(tfId.getText()));
produto.setCodigo(tfCodigo.getText());
produto.setNome(tfNome.getText());
produto.setValor(Double.parseDouble(tfValor.getText()));
produto.setFornecedor(
tfId.setText(String.valueOf(p.getId()));
tfCodigo.setText(p.getCodigo());
tfNome.setText(p.getNome());
tfValor.setText(String.valueOf(p.getValor()));
cbFornecedor.setSelectedItem(p.getFornecedor().getNome());
try
getFornecedor();
produtoDao.cadastrar(produto);
limparCampos();
JOptionPane.showMessageDialog(null,
private
//Cdigo
catch
(!tfId.getText().equals(""))
{ void
(Exception
omitido
getFornecedor()
setFornecedor(Produto
btFecharActionPerformed(java.awt.event.ActionEvent
ex) {fornecedorDao.pesquisar(
throws
{ p)ex);
Exception{
"Cadastrado
{
evt)
com{
btPesquisarActionPerformed(java.awt.event.ActionEvent
try
produtos
298
299
301
300
JOptionPane.showMessageDialog(null,
302
303
306
310
309
posicao++;
308
313
if
317
316
posicao--;
315
320
323
322
325
evt)
}posicao
328
setFornecedor(produtos.get(posicao));
327
private
{330
3229
97catch
04
05
07
11
12
14
18
19
21
24
26
(posicao
{ void
=(Exception
=produtos.size()
0;produtoDao.pesquisar(tfNome.getText());
><btAlterarActionPerformed(java.awt.event.ActionEvent
btProximoActionPerformed(java.awt.event.ActionEvent
btAnteriorActionPerformed(java.awt.event.ActionEvent
btPrimeiroActionPerformed(java.awt.event.ActionEvent
btUltimoActionPerformed(java.awt.event.ActionEvent
produtos.size()
0)
{ ex) { - 1;- 1) {ex);
331 try {
332 getFornecedor();
333 produtoDao.alterar(produto);
334 JOptionPane.showMessageDialog(null, "Alterado com sucesso!");
335 limparCampos();
336 } catch (Exception ex) {
337 JOptionPane.showMessageDialog(null, ex);
338
}
339
} 340
341 private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {
342 try {
343 getFornecedor();
344 produtoDao.excluir(produto.getId());
345 JOptionPane.showMessageDialog(null, "Excluido com sucesso!");
346 limparCampos();
347 } catch (Exception ex) {
348 JOptionPane.showMessageDialog(null, ex);
349
}
350
} 351
352 private void btNovoActionPerformed(java.awt.event.ActionEvent evt) {
353 limparCampos();
354
} 355
356
//Cdigo omitido 382
383 /* Create and display the form */
384 java.awt.EventQueue.invokeLater(new Runnable() {
385 public void run() {
386 try {
387 new FormularioFornecedor().setVisible(true);
388 } catch (Exception ex) {
389 JOptionPane.showMessageDialog(null, ex);
390
}
391
}
392
});
393
394
395
396
397
398
399
400
401
402
403
404

}
// Variables declaration - do not modify
private javax.swing.JButton btAlterar;
private javax.swing.JButton btAnterior;
private javax.swing.JButton btCadastrar;
private javax.swing.JButton btExcluir;
private javax.swing.JButton btFechar;
private javax.swing.JButton btNovo;
private javax.swing.JButton btPesquisar;
private javax.swing.JButton btPrimeiro;
private javax.swing.JButton btProximo;
private javax.swing.JButton btUltimo;

405
406
407
408
409
410
411
412
413
414
415
416

private javax.swing.JComboBox cbFornecedor;


private javax.swing.JButton jButton10;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField tfCodigo;
private javax.swing.JTextField tfId;
private javax.swing.JTextField tfNome;
private javax.swing.JTextField tfValor;
// End of variables declaration 417 }

Entrada

btBuscarActionPerformed(java.awt.event.ActionEvent
void
private
155
156
157
158
159
160
161
162
164
163
btRegistrarActionPerformed(java.awt.event.ActionEvent
165
166
167
168
171
movimento.setQuantidade(Double.parseDouble(tfQtde.getText()));
170
movimento.setProduto(produtoDao.pesquisar(tfProduto.getText()).get(0));
169
173
172
174
175
177
176
178
179
180
181
182
183
185
184
evt)
186
187
236
215
}{ }dispose();
trycatch
new
FormularioBuscar.formulario="Entrada";
try{
ProdutoDao
Movimento
movimento.setTipo(tfTipo.getText());
movimento.setData(tfData.getText());
MovimentoDao
movimentoDao.registarMovimento(movimento);
tfProduto.setText(null);
tfQtde.setText(null);
tfData.setText(null);
}catch(Exception
JOptionPane.showMessageDialog(null,
private
{ void
FormularioBuscar().show();
(Exception
movimento
produtoDao
movimentoDao
jButton1ActionPerformed(java.awt.event.ActionEvent
ex){
ex)
= new
={new=Movimento();
ProdutoDao();
new
MovimentoDao();
"Entrada registada!");
ex);
evt) {
Busca de produtos

18 List<Produto> produtos = new LinkedList<>();


19 public static String formulario=""; 20
/**
21
* Creates new form FormularioBuscar 22 */
23 public FormularioBuscar() throws Exception{
24 initComponents(); 25 }
26
116
117 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
118 try{
119 produtos = produtoDao.pesquisar(tfProduto.getText());
120 DefaultTableModel tabela = (DefaultTableModel) tbProduto.getModel();
121 for(int i=0; i<produtos.size();i++){
122 tabela.addRow(new Object[]{produtos.get(i).getCodigo(),
123 produtos.get(i).getNome(),
124 produtos.get(i).getFornecedor().getNome(),
125 produtos.get(i).getValor(),
126 produtos.get(i).getEstoque() });
127
}
128 }catch(Exception ex){
129 JOptionPane.showMessageDialog(null, ex);
130
}
131
} 132
133 private void tbProdutoMouseClicked(java.awt.event.MouseEvent evt) {
134 if(evt.getClickCount()==2){
135 String nome = tbProduto.getValueAt(tbProduto.getSelectedRow(), 1).toString()
;
136 if(formulario.equals("Entrada")){
137 FormularioEntrada.tfProduto.setText(nome);
138 }else if(formulario.equals("Sada")){
139 FormularioSaida.tfProduto.setText(nome);
140
}

141
142

dispose();
}

143
/*
172
171
java.awt.EventQueue.invokeLater(new
173
public
174
try
175
new
176
177
JOptionPane.showMessageDialog(null,
178
}179
182
});
184
185
186
187
private
188
//
189
190
191
183
44catch
80
81
Create
Variables
End
{ of
}FormularioBuscar().setVisible(true);
void
(Exception
javax.swing.JButton
javax.swing.JLabel
javax.swing.JScrollPane
javax.swing.JTable
javax.swing.JTextField
andrun()
variables
declaration
display
{ex)
declaration
the
{ -form
dojButton1;
jLabel1;
tbProduto;
not
*/jScrollPane1;
tfProduto;
modify
Runnable() {
ex);

Sada

154 { private
153
155
156
157
158
159
160
161
163
162
btRegistrarActionPerformed(java.awt.event.ActionEvent
164
165
166
167
170
movimento.setQuantidade(Double.parseDouble(tfQtde.getText()));
169
movimento.setProduto(produtoDao.pesquisar(tfProduto.getText()).get(0));
168
172
171
173
174
176
175
177
178
179
180
181
182
183
184
185
187
{186
evt)
newcatch
FormularioBuscar.formulario="Sada";
try
ProdutoDao
Movimento
movimento.setTipo(tfTipo.getText());
movimento.setData(tfData.getText());
MovimentoDao
if
tfProduto.setText(null);
tfQtde.setText(null);
tfData.setText(null);
}JOptionPane.showMessageDialog(null,
else
(movimentoDao.registarMovimento(movimento))
{FormularioBuscar().show();
{void
(Exception
movimento
produtoDao
btBuscarActionPerformed(java.awt.event.ActionEvent
movimentoDao
jButton1ActionPerformed(java.awt.event.ActionEvent
ex)
= new
={new=Movimento();
ProdutoDao();
new
MovimentoDao();
"Sada registada!");
"Estoque
ex);
insuficiente");
evt)
{ {

REFENRNCIAS BIBLIOGRFICAS
TEIXEIRA, Maria. Acesso a Banco de Dados com JDBC (Java Database Connectivity) e
o Padro de Projeto DAO (Data Access Object). Disponvel em http://www.ceunes.ufes.
br/downloads/2
/mariateixeira-Java.Introdu%C3%A7%C3%A3o%20a%20Banco% 20de%20Dados.pdf. Acessado
em 17 de outubro de 2012.
CARNEIRO, Davi Luan. Introduo ao pattern DAO. Disponvel em http://javafree.uol.com.
br/artigo/871452/Introducao-ao-pattern- DAO.html. Acessado em 17 de outubro de 2
012

You might also like