Skip to content

Commit b0fbd2a

Browse files
committed
refatoracao e heranca
1 parent 95f9fd9 commit b0fbd2a

File tree

13 files changed

+283
-124
lines changed

13 files changed

+283
-124
lines changed

src/main/java/com/example/AppBd.java

Lines changed: 28 additions & 120 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,15 @@
55
import java.sql.SQLException;
66
import java.sql.Statement;
77

8-
public class AppBd {
8+
import com.example.dao.ConnectionManager;
9+
import com.example.dao.DAO;
10+
import com.example.dao.EstadoDAO;
11+
import com.example.dao.ProdutoDAO;
12+
import com.example.model.Estado;
13+
import com.example.model.Marca;
14+
import com.example.model.Produto;
915

10-
private static final String PASSWORD = "";
11-
private static final String USERNAME = "gitpod";
12-
private static final String JDBC_URL = "jdbc:postgresql://localhost/postgres";
16+
public class AppBd {
1317

1418
public static void main(String[] args) {
1519

@@ -18,11 +22,18 @@ public static void main(String[] args) {
1822
}
1923

2024
public AppBd() {
21-
try (var conn = getConnection()) {
25+
try (var conn = ConnectionManager.getConnection()) {
2226

23-
listarEstados(conn);
2427

25-
localizarEstado(conn, "CE");
28+
var estadoDAO = new EstadoDAO(conn);
29+
30+
var listaEstados = estadoDAO.listar();
31+
32+
for(Estado estado : listaEstados){
33+
System.out.println(estado);
34+
}
35+
36+
estadoDAO.localizar("CE");
2637

2738

2839

@@ -42,130 +53,27 @@ public AppBd() {
4253
produto.setNome("Produto Novo (alterado)");
4354
produto.setValor(90);
4455

45-
//inserirProduto(conn, produto);
46-
alterarProduto(conn, produto);
47-
excluirProduto(conn, 203L);
48-
49-
listarDadosTabela(conn, "produto");
50-
} catch (SQLException e) {
51-
System.err.println("Não foi possível conectar ao banco de dados: " + e.getMessage());
52-
}
53-
}
54-
55-
private void excluirProduto(Connection conn, long id) {
56-
var sql = "delete from produto where id = ?";
57-
58-
try {
59-
var statement = conn.prepareStatement(sql);
60-
statement.setLong(1, id);
61-
if(statement.executeUpdate() == 1){
62-
System.out.printf("\nProduto %d excluido \n", id);
63-
} else System.out.println("Produto não localizado");
64-
} catch (SQLException e) {
65-
System.err.println("Erro ao excluir: " + e.getMessage());
66-
}
67-
68-
}
6956

70-
private void inserirProduto(Connection conn, Produto produto){
71-
var sql = "insert into produto (nome, marca_id, valor) values (? , ?, ?)";
72-
try {
73-
var statement = conn.prepareStatement(sql);
74-
statement.setString(1, produto.getNome());
75-
statement.setLong(2, produto.getMarca().getId());
76-
statement.setDouble(3, produto.getValor());
77-
statement.executeUpdate();
78-
} catch (SQLException e) {
79-
System.err.println("Erro na execução da consulta: " + e.getMessage());
80-
};
81-
}
8257

58+
var produtoDAO = new ProdutoDAO(conn);
59+
//inserirProduto(conn, produto);
60+
produtoDAO.alterar(produto);
61+
produtoDAO.excluir(203L);
8362

84-
private void alterarProduto(Connection conn, Produto produto){
85-
var sql = "update produto set nome = ?, marca_id = ?, valor = ? where id = ?";
86-
try {
87-
var statement = conn.prepareStatement(sql);
88-
statement.setString(1, produto.getNome());
89-
statement.setLong(2, produto.getMarca().getId());
90-
statement.setDouble(3, produto.getValor());
91-
statement.setLong(4, produto.getId());
92-
statement.executeUpdate();
93-
} catch (SQLException e) {
94-
System.err.println("Erro na alteração do produto: " + e.getMessage());
95-
};
96-
}
97-
98-
private void listarDadosTabela(Connection conn, String tabela) {
99-
var sql = "select * from " + tabela;
100-
//System.out.println(sql);
101-
try{
102-
var statement = conn.createStatement();
103-
var result = statement.executeQuery(sql);
104-
105-
var metadata = result.getMetaData();
106-
int cols = metadata.getColumnCount();
107-
108-
for(int i = 1; i <= cols; i++){
109-
System.out.printf("%-10s | ", metadata.getColumnName(i));
110-
}
111-
System.out.println();
112-
113-
while(result.next()){
114-
115-
for(int i = 1; i <= cols; i++){
116-
System.out.printf("%-10s | ", result.getString(i));
117-
}
118-
System.out.println();
119-
}
120-
} catch(SQLException e){
121-
System.err.println("Erro na execução da consulta: " + e.getMessage());
122-
}
123-
124-
}
125-
126-
private void localizarEstado(Connection conn, String uf) {
127-
try {
63+
//var dao = new DAO(conn);
12864

129-
// var sql = "select * from estado where uf = '" + uf + "'"; >>> SUCETÍVEL A SQL
130-
// INJECTION
65+
//dao.listar("produto");
13166

132-
var sql = "select * from estado where uf = ?";
133-
var statement = conn.prepareStatement(sql);
134-
statement.setString(1, uf);
135-
var result = statement.executeQuery();
136-
if (result.next()) {
137-
System.out.printf("Id: %d Nome: %s UF: %s \n", result.getInt("id"), result.getString("nome"),
138-
result.getString("uf"));
139-
}
14067
} catch (SQLException e) {
141-
System.err.println("Erro ao executar consulta sql: " + e.getMessage());
68+
System.err.println("Não foi possível conectar ao banco de dados: " + e.getMessage());
14269
}
14370
}
14471

145-
private void listarEstados(Connection conn) {
146-
147-
try {
148-
149-
System.out.println("conexão realizada com sucesso.");
150-
151-
var statement = conn.createStatement();
152-
var result = statement.executeQuery("select * from estado");
153-
154-
while (result.next()) {
155-
System.out.printf("Id: %d Nome: %s UF: %s \n", result.getInt("id"), result.getString("nome"),
156-
result.getString("UF"));
157-
}
158-
System.out.println();
159-
} catch (SQLException e) {
160-
161-
System.out.println("Não foi possível executar a consulta ao banco: " + e.getMessage());
72+
16273

163-
}
164-
}
74+
16575

166-
private Connection getConnection() throws SQLException {
167-
return DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
168-
}
76+
16977

17078
private void carregarDriverJDBC() {
17179
try {

src/main/java/com/example/AppIdades.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import java.time.format.DateTimeFormatter;
55
import java.util.Date;
66

7+
import com.example.model.Cidadao;
8+
79
public class AppIdades {
810
public static void main(String[] args) {
911
System.out.println("uobaaa");

src/main/java/com/example/AppListas.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import java.util.ArrayList;
44
import java.util.List;
55

6+
import com.example.model.Cliente;
7+
68

79
public class AppListas {
810
public static void main(String[] args) {
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.example.dao;
2+
3+
import java.sql.Connection;
4+
import java.sql.DriverManager;
5+
import java.sql.SQLException;
6+
7+
public class ConnectionManager {
8+
9+
private static final String PASSWORD = "";
10+
private static final String USERNAME = "gitpod";
11+
private static final String JDBC_URL = "jdbc:postgresql://localhost/postgres";
12+
13+
public static Connection getConnection() throws SQLException {
14+
return DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
15+
}
16+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.example.dao;
2+
3+
import java.sql.Connection;
4+
import java.sql.SQLException;
5+
6+
public class DAO {
7+
protected Connection conn;
8+
// protected = classes filhas e no mesmo pacote podem ter acesso a esse mesmo atributo
9+
10+
public DAO(Connection conn){
11+
this.conn = conn;
12+
}
13+
14+
15+
public void listar(String tabela) {
16+
var sql = "select * from " + tabela;
17+
//System.out.println(sql);
18+
try{
19+
var statement = conn.createStatement();
20+
var result = statement.executeQuery(sql);
21+
22+
var metadata = result.getMetaData();
23+
int cols = metadata.getColumnCount();
24+
25+
for(int i = 1; i <= cols; i++){
26+
System.out.printf("%-10s | ", metadata.getColumnName(i));
27+
}
28+
System.out.println();
29+
30+
while(result.next()){
31+
32+
for(int i = 1; i <= cols; i++){
33+
System.out.printf("%-10s | ", result.getString(i));
34+
}
35+
System.out.println();
36+
}
37+
} catch(SQLException e){
38+
System.err.println("Erro na execução da consulta: " + e.getMessage());
39+
}
40+
41+
}
42+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package com.example.dao;
2+
3+
import java.sql.Connection;
4+
import java.sql.SQLException;
5+
import java.util.LinkedList;
6+
import java.util.List;
7+
8+
import com.example.model.Estado;
9+
10+
public class EstadoDAO extends DAO{
11+
12+
public EstadoDAO(Connection conn) {
13+
super(conn);
14+
}
15+
16+
public List<Estado> listar() throws SQLException {
17+
var lista = new LinkedList<Estado>();
18+
19+
var statement = conn.createStatement();
20+
var result = statement.executeQuery("select * from estado");
21+
22+
while (result.next()) {
23+
var estado = new Estado();
24+
25+
estado.setId(result.getLong("id"));
26+
27+
estado.setNome(result.getString("nome"));
28+
29+
estado.setUf(result.getString("uf"));
30+
31+
lista.add(estado);
32+
33+
}
34+
System.out.println();
35+
36+
return lista;
37+
}
38+
39+
public void localizar(String uf) {
40+
try {
41+
42+
// var sql = "select * from estado where uf = '" + uf + "'"; >>> SUCETÍVEL A SQL
43+
// INJECTION
44+
45+
var sql = "select * from estado where uf = ?";
46+
var statement = conn.prepareStatement(sql);
47+
statement.setString(1, uf);
48+
var result = statement.executeQuery();
49+
if (result.next()) {
50+
System.out.printf("Id: %d Nome: %s UF: %s \n", result.getInt("id"), result.getString("nome"),
51+
result.getString("uf"));
52+
}
53+
} catch (SQLException e) {
54+
System.err.println("Erro ao executar consulta sql: " + e.getMessage());
55+
}
56+
}
57+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.example.dao;
2+
3+
import java.sql.Connection;
4+
import java.sql.SQLException;
5+
6+
import com.example.model.Produto;
7+
8+
public class ProdutoDAO extends DAO {
9+
10+
11+
public ProdutoDAO(Connection conn){
12+
super(conn);
13+
}
14+
15+
16+
public void excluir(long id) {
17+
var sql = "delete from produto where id = ?";
18+
19+
try {
20+
var statement = conn.prepareStatement(sql);
21+
statement.setLong(1, id);
22+
if(statement.executeUpdate() == 1){
23+
System.out.printf("\nProduto %d excluido \n", id);
24+
} else System.out.println("Produto não localizado");
25+
} catch (SQLException e) {
26+
System.err.println("Erro ao excluir: " + e.getMessage());
27+
}
28+
29+
}
30+
31+
public void inserir(Produto produto){
32+
var sql = "insert into produto (nome, marca_id, valor) values (? , ?, ?)";
33+
try {
34+
var statement = conn.prepareStatement(sql);
35+
statement.setString(1, produto.getNome());
36+
statement.setLong(2, produto.getMarca().getId());
37+
statement.setDouble(3, produto.getValor());
38+
statement.executeUpdate();
39+
} catch (SQLException e) {
40+
System.err.println("Erro na execução da consulta: " + e.getMessage());
41+
};
42+
}
43+
44+
45+
public void alterar(Produto produto){
46+
var sql = "update produto set nome = ?, marca_id = ?, valor = ? where id = ?";
47+
try {
48+
var statement = conn.prepareStatement(sql);
49+
statement.setString(1, produto.getNome());
50+
statement.setLong(2, produto.getMarca().getId());
51+
statement.setDouble(3, produto.getValor());
52+
statement.setLong(4, produto.getId());
53+
statement.executeUpdate();
54+
} catch (SQLException e) {
55+
System.err.println("Erro na alteração do produto: " + e.getMessage());
56+
};
57+
}
58+
}

src/main/java/com/example/Cidadao.java renamed to src/main/java/com/example/model/Cidadao.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.example;
1+
package com.example.model;
22

33
import java.time.LocalDate;
44

src/main/java/com/example/Cliente.java renamed to src/main/java/com/example/model/Cliente.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.example;
1+
package com.example.model;
22

33
public class Cliente {
44

0 commit comments

Comments
 (0)