Como criar uma lista de endereços, uma lista de contatos?

2 respostas
M

boa noite !!! bom.. para estudos, quero desenvolver, por exemplo, onde em um cadastro de clientes, o mesmo cliente pode ter varios endereços, tipo comercial, residencial etc,
e varios contatos, como tio, avo, pai etc. o que eu fiz, com muita pesquisa, consegui chegar no cadastro do cliente em si, adicionando no banco de dados, removendo, alterando o nome do cliente,
o endereço etc. mas o que não estou conseguindo visualizar em como fazer no meu código, é por exemplo, é adicionar um cliente com mais de um endereço ( pensei na enum ) ,
adicionar contatos para o mesmo cliente , será que vcs poderiam me dar o começo, partindo do meu código de como começar

segue abaixo:

a classe Cliente:
public class Cliente {

	private long id;
	private String nome;
	private String endereco;
	private String tel;
	private String email;
	private String sexo;

	/*public Contato(long id, String nome, String endereco, String tel,
			String email, String sexo) {
		super();
		this.id = id;
		this.nome = nome;
		this.endereco = endereco;
		this.tel = tel;
		this.email = email;
		this.sexo = sexo;
	}*/


	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;
	}

	public String getEndereco() {
		return endereco;
	}

	public void setEndereco(String endereco) {
		this.endereco = endereco;
	}

	public String getTel() {
		return tel;
	}

	public void setTel(String tel) {
		this.tel = tel;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getSexo() {
		return sexo;
	}

	public void setSexo(String sexo) {
		this.sexo = sexo;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((email == null) ? 0 : email.hashCode());
		result = prime * result
				+ ((endereco == null) ? 0 : endereco.hashCode());
		result = prime * result + (int) (id ^ (id >>> 32));
		result = prime * result + ((nome == null) ? 0 : nome.hashCode());
		result = prime * result + ((sexo == null) ? 0 : sexo.hashCode());
		result = prime * result + ((tel == null) ? 0 : tel.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Contato other = (Contato) obj;
		if (email == null) {
			if (other.email != null)
				return false;
		} else if (!email.equals(other.email))
			return false;
		if (endereco == null) {
			if (other.endereco != null)
				return false;
		} else if (!endereco.equals(other.endereco))
			return false;
		if (id != other.id)
			return false;
		if (nome == null) {
			if (other.nome != null)
				return false;
		} else if (!nome.equals(other.nome))
			return false;
		if (sexo == null) {
			if (other.sexo != null)
				return false;
		} else if (!sexo.equals(other.sexo))
			return false;
		if (tel == null) {
			if (other.tel != null)
				return false;
		} else if (!tel.equals(other.tel))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Contato [email=" + email + ", endereco=" + endereco + ", id="
				+ id + ", nome=" + nome + ", sexo=" + sexo + ", tel=" + tel
				+ "]";
	}

}

a classe ContatoDao :

public class ContatoDao {

	private Connection conexao;

	public ContatoDao() throws SQLException {

		this.conexao = CriaConexao.getConexao();

	}

	public void adiciona(Contato c1) throws SQLException {

		// prepara a conexao

		String sql = "insert into contato (nome, endereco, telefone, email, sexo)"
				+ " values (?,?,?,?,?)";

		PreparedStatement stmt = conexao.prepareStatement(sql);

		// set os valores

		stmt.setString(1, c1.getNome());
		stmt.setString(2, c1.getEndereco());
		stmt.setString(3, c1.getTel());
		stmt.setString(4, c1.getEmail());
		stmt.setString(5, c1.getSexo());

		// executa

		stmt.execute();
		stmt.close();

		JOptionPane.showMessageDialog(null, "Adicionado ao banco");

	}

	public List<Contato> getLista() throws SQLException {

		String sql = "select * from contato";
		PreparedStatement stmt = this.conexao.prepareStatement(sql);
		ResultSet rset = stmt.executeQuery(); // pesquisou com o rset e guarda
		// na lista

		List<Contato> listaContato = new LinkedList<Contato>();

		while (rset.next()) {
			Contato c1 = new Contato(); // tive que tirar o construtor, porque ?

			c1.setNome(rset.getString("nome"));
			c1.setNome(rset.getString("endereco"));
			c1.setNome(rset.getString("telefone"));
			c1.setNome(rset.getString("email"));
			c1.setNome(rset.getString("sexo"));

			listaContato.add(c1);

		}

		rset.close();
		stmt.close();
		return listaContato;

	}

	public void alterar(Contato c1) throws SQLException {

		String sql = "update contato set nome=?m endereco=?, telefone=?, email=?, sexo=? where id=?";
		PreparedStatement stmt = conexao.prepareStatement(sql);

		stmt.setString(1, c1.getNome());
		stmt.setString(2, c1.getEndereco());
		stmt.setString(3, c1.getTel());
		stmt.setString(4, c1.getEmail());
		stmt.setString(5, c1.getSexo());
		stmt.setLong(6, c1.getId()); // porque o id ?

		stmt.execute();
		stmt.close();

	}

	public void remove(Contato c1) throws SQLException {

		String sql = "remove from contato where id=?";
		PreparedStatement stmt = conexao.prepareStatement(sql);
		stmt.setLong(1, c1.getId());

		stmt.execute();
		stmt.close();

	}

}

a classe main :

public class Main {

	public static void conectar() throws SQLException {

		Connection conexao = new CriaConexao().getConexao();

	}

	public static void adicionarContato() throws SQLException {

		Contato contato = new Contato();

		contato.setNome("Marcelo Paulo 3");
		contato.setEndereco("Av Abel Correia");
		contato.setTel("[telefone removido]");
		contato.setEmail("[email removido]");
		contato.setSexo("m");

		ContatoDao dao = new ContatoDao();

		dao.adiciona(contato);

	}

	public static void alterarContatos() throws SQLException {

		Contato contato = new Contato();

		contato.setId(Long.valueOf(4)); // altera direto na posicao
		contato.setNome("Marcelo Paulo Rebello Martins");
		contato.setEndereco("Av Abel Correia");
		contato.setTel("[telefone removido]");
		contato.setEmail("[email removido]");
		contato.setSexo("m");

		ContatoDao dao = new ContatoDao();

		dao.alterar(contato);

	}

	public static void removeContatos() throws SQLException {

		Contato contato = new Contato();
		contato.setId(Long.valueOf(6));

		ContatoDao dao = new ContatoDao();

		dao.remove(contato);

	}

	public static void listaContatos() throws SQLException {

		ContatoDao dao = new ContatoDao();

		List<Contato> listaContatos = dao.getLista();

		for (Contato contato : listaContatos) {
			JOptionPane.showMessageDialog(null,
					"------------------------------------------" + ""
							+ " \nNome: " + "" + contato.getNome() + "\nEndereco : " + "" + contato.getEndereco());
						
							/*+ "\nEndereco : " + "" + contato.getEndereco() + ""
							+ "\n Telefone : " + "" + contato.getTel()
							+ "\nemail : " + "" + contato.getEmail()
							+ "\nTelefone : " + "" + contato.getTel()
							+ "\n-----------------------------------------" ); */
		}

	}

	public static void main(String[] args) throws SQLException {

		conectar();
	//	adicionarContato();
		// alterarContatos();
		// removeContatos();
		listaContatos();

	}
}

2 Respostas

ViniGodoy

Crie uma classe Endereco, contendo os dados do endereço.
E seu Cliente terá uma lista de endereços ( List<Endereco> ).

No seu banco, isso varia uma tabela: Endereco e uma relação de 1-N entre as tabelas Cliente e Endereco.

M

então vinny… criei a classe endereco… e um endereco.Dao ( posso fazer desta forma ) certo ? , e criei a tabela…
mas não consegui ver em como fazer a ligação entre o cliente e o endereço. como eu faria ?

Criado 10 de setembro de 2011
Ultima resposta 10 de set. de 2011
Respostas 2
Participantes 2