import java.io.*;
import java.sql.*;
import java.util.*;
import java.math.*;
public class Cliente implements Cloneable, Serializable {
private String codigo;
private String nome;
private String tipo;
public Cliente () {
}
public Cliente (String codigoIn) {
this.codigo = codigoIn;
}
/**
* Get- and Set-methods for persistent variables.
*/
public String getCodigo() {
return this.codigo;
}
public void setCodigo(String codigoIn) {
this.codigo = codigoIn;
}
public String getNome() {
return this.nome;
}
public void setNome(String nomeIn) {
this.nome = nomeIn;
}
public String getTipo() {
return this.tipo;
}
public void setTipo(String tipoIn) {
this.tipo = tipoIn;
}
/**
* setAll allows to set all persistent variables in one method call.
*/
public void setAll(String codigoIn,
String nomeIn,
String tipoIn) {
this.codigo = codigoIn;
this.nome = nomeIn;
this.tipo = tipoIn;
}
/**
* hasEqualMapping-method will compare two Cliente instances
* and return true if they contain same values in all persistent instance
* variables.
*/
public boolean hasEqualMapping(Cliente valueObject) {
if (this.codigo == null) {
if (valueObject.getCodigo() != null)
return(false);
} else if (!this.codigo.equals(valueObject.getCodigo())) {
return(false);
}
if (this.nome == null) {
if (valueObject.getNome() != null)
return(false);
} else if (!this.nome.equals(valueObject.getNome())) {
return(false);
}
if (this.tipo == null) {
if (valueObject.getTipo() != null)
return(false);
} else if (!this.tipo.equals(valueObject.getTipo())) {
return(false);
}
return true;
}
public String toString() {
StringBuffer out = new StringBuffer(this.getDaogenVersion());
out.append("\nclass Cliente, mapping to table Cliente\n");
out.append("Persistent attributes: \n");
out.append("codigo = " + this.codigo + "\n");
out.append("nome = " + this.nome + "\n");
out.append("tipo = " + this.tipo + "\n");
return out.toString();
}
/**
* Clone will return identical deep copy of this valueObject.
*/
public Object clone() {
Cliente cloned = new Cliente();
if (this.codigo != null)
cloned.setCodigo(new String(this.codigo));
if (this.nome != null)
cloned.setNome(new String(this.nome));
if (this.tipo != null)
cloned.setTipo(new String(this.tipo));
return cloned;
}
}
// ClienteDao
import java.sql.*;
import java.util.*;
import java.math.*;
public class ClienteDao {
public Cliente createValueObject() {
return new Cliente();
}
public Cliente getObject(Connection conn, String codigo) throws NotFoundException, SQLException {
Cliente valueObject = createValueObject();
valueObject.setCodigo(codigo);
load(conn, valueObject);
return valueObject;
}
public void load(Connection conn, Cliente valueObject) throws NotFoundException, SQLException {
if (valueObject.getCodigo() == null) {
//System.out.println("Can not select without Primary-Key!");
throw new NotFoundException("Can not select without Primary-Key!");
}
String sql = "SELECT * FROM Cliente WHERE (codigo = ? ) ";
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(sql);
stmt.setString(1, valueObject.getCodigo());
singleQuery(conn, stmt, valueObject);
} finally {
if (stmt != null)
stmt.close();
}
}
public List loadAll(Connection conn) throws SQLException {
String sql = "SELECT * FROM Cliente ORDER BY codigo ASC ";
List searchResults = listQuery(conn, conn.prepareStatement(sql));
return searchResults;
}
public synchronized void create(Connection conn, Cliente valueObject) throws SQLException {
String sql = "";
PreparedStatement stmt = null;
ResultSet result = null;
try {
sql = "INSERT INTO Cliente ( codigo, nome, tipo) VALUES (?, ?, ?) ";
stmt = conn.prepareStatement(sql);
stmt.setString(1, valueObject.getCodigo());
stmt.setString(2, valueObject.getNome());
stmt.setString(3, valueObject.getTipo());
int rowcount = databaseUpdate(conn, stmt);
if (rowcount != 1) {
//System.out.println("PrimaryKey Error when updating DB!");
throw new SQLException("PrimaryKey Error when updating DB!");
}
} finally {
if (stmt != null)
stmt.close();
}
}
public void save(Connection conn, Cliente valueObject)
throws NotFoundException, SQLException {
String sql = "UPDATE Cliente SET nome = ?, tipo = ? WHERE (codigo = ? ) ";
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(sql);
stmt.setString(1, valueObject.getNome());
stmt.setString(2, valueObject.getTipo());
stmt.setString(3, valueObject.getCodigo());
int rowcount = databaseUpdate(conn, stmt);
if (rowcount == 0) {
//System.out.println("Object could not be saved! (PrimaryKey not found)");
throw new NotFoundException("Object could not be saved! (PrimaryKey not found)");
}
if (rowcount > 1) {
//System.out.println("PrimaryKey Error when updating DB! (Many objects were affected!)");
throw new SQLException("PrimaryKey Error when updating DB! (Many objects were affected!)");
}
} finally {
if (stmt != null)
stmt.close();
}
}
public void delete(Connection conn, Cliente valueObject)
throws NotFoundException, SQLException {
if (valueObject.getCodigo() == null) {
//System.out.println("Can not delete without Primary-Key!");
throw new NotFoundException("Can not delete without Primary-Key!");
}
String sql = "DELETE FROM Cliente WHERE (codigo = ? ) ";
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(sql);
stmt.setString(1, valueObject.getCodigo());
int rowcount = databaseUpdate(conn, stmt);
if (rowcount == 0) {
//System.out.println("Object could not be deleted (PrimaryKey not found)");
throw new NotFoundException("Object could not be deleted! (PrimaryKey not found)");
}
if (rowcount > 1) {
//System.out.println("PrimaryKey Error when updating DB! (Many objects were deleted!)");
throw new SQLException("PrimaryKey Error when updating DB! (Many objects were deleted!)");
}
} finally {
if (stmt != null)
stmt.close();
}
}
public void deleteAll(Connection conn) throws SQLException {
String sql = "DELETE FROM Cliente";
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(sql);
int rowcount = databaseUpdate(conn, stmt);
} finally {
if (stmt != null)
stmt.close();
}
}
public int countAll(Connection conn) throws SQLException {
String sql = "SELECT count(*) FROM Cliente";
PreparedStatement stmt = null;
ResultSet result = null;
int allRows = 0;
try {
stmt = conn.prepareStatement(sql);
result = stmt.executeQuery();
if (result.next())
allRows = result.getInt(1);
} finally {
if (result != null)
result.close();
if (stmt != null)
stmt.close();
}
return allRows;
}
public List searchMatching(Connection conn, Cliente valueObject) throws SQLException {
List searchResults;
boolean first = true;
StringBuffer sql = new StringBuffer("SELECT * FROM Cliente WHERE 1=1 ");
if (valueObject.getCodigo() != null) {
if (first) { first = false; }
sql.append("AND codigo LIKE '").append(valueObject.getCodigo()).append("%' ");
}
if (valueObject.getNome() != null) {
if (first) { first = false; }
sql.append("AND nome LIKE '").append(valueObject.getNome()).append("%' ");
}
if (valueObject.getTipo() != null) {
if (first) { first = false; }
sql.append("AND tipo LIKE '").append(valueObject.getTipo()).append("%' ");
}
sql.append("ORDER BY codigo ASC ");
// Prevent accidential full table results.
// Use loadAll if all rows must be returned.
if (first)
searchResults = new ArrayList();
else
searchResults = listQuery(conn, conn.prepareStatement(sql.toString()));
return searchResults;
}
public String getDaogenVersion() {
return "DaoGen version 2.4.1";
}
protected int databaseUpdate(Connection conn, PreparedStatement stmt) throws SQLException {
int result = stmt.executeUpdate();
return result;
}
protected void singleQuery(Connection conn, PreparedStatement stmt, Cliente valueObject)
throws NotFoundException, SQLException {
ResultSet result = null;
try {
result = stmt.executeQuery();
if (result.next()) {
valueObject.setCodigo(result.getString("codigo"));
valueObject.setNome(result.getString("nome"));
valueObject.setTipo(result.getString("tipo"));
} else {
//System.out.println("Cliente Object Not Found!");
throw new NotFoundException("Cliente Object Not Found!");
}
} finally {
if (result != null)
result.close();
if (stmt != null)
stmt.close();
}
}
protected List listQuery(Connection conn, PreparedStatement stmt) throws SQLException {
ArrayList searchResults = new ArrayList();
ResultSet result = null;
try {
result = stmt.executeQuery();
while (result.next()) {
Cliente temp = createValueObject();
temp.setCodigo(result.getString("codigo"));
temp.setNome(result.getString("nome"));
temp.setTipo(result.getString("tipo"));
searchResults.add(temp);
}
} finally {
if (result != null)
result.close();
if (stmt != null)
stmt.close();
}
return (List)searchResults;
}
}
Duvida Dao
Olá! Pessoal, estou com um probleminha pra entender DAO. :oops: Fiz no daogen e saiu as classes TO e DAO, já copiei e colei com os nomes que eles indicam e tal... o problema é que não tô sabendo onde eu vou fazer os métodos (as funcionalidades deles) ??? Tipo cadstrar, pesquisar, etc... as milhões de coisas que o programa tem que ter pra funcionar. Fiz o BD e o frame principal para fazer o cadstro,renovacao,pesquisa, etc, mas nao sei em qual tenho que colocar o que cada metodo tem que fazer, se é que voces estão entendendo :shock:
o ClienteDao.java e a classe Cliente.java:
2 Respostas
cara acho q sa duvida e em conceito,primeiro tenta entender para q server cada classe,tipo a DAO vem de DAOFactory(FABRICA),ela representara sua digamos sua maleta de ferramentas, tudo q vc precisar tem q estar nela,mas nao em termos de metodos para tudo e sim tipo pegar conexao,pegar um objeto do banco de dados,a manipulacao desses objetos ai voce trata em outra classe, entendeu um pouco ???
Meu problema ta aí, tratar em outra classe. Que classe??? Entendeu??? Não sei qual dessas classes, ou até mesmo, se tem que criar outra classe pra tratar os objetos.
Criado 29 de maio de 2008
Ultima resposta 29 de mai. de 2008
Respostas 2
Participantes 2
Alura POO: o que é programação orientada a objetos? Aprenda os conceitos básicos da programação orientada a objetos, como classes, objetos, herança, encapsulamento e polimorfismo, com exemplos.
Casa do Codigo Inteligencia Artificial e ChatGPT: Da revolucao dos... Por Fabricio Carraro — Casa do Codigo