Link two classes

0

Hello, everyone!

I'm developing a college job which is a mini banking system with Java SE and I'm using Swing for interface. I have a bit of trouble with the OO paradigm and wanted to know how I can relate a client class to a class account. In the database, I used foreign key to relate my table cliente to table conta . But in Java classes? How do I associate a new account with an existing customer? I have already tested my client crud and it is working. This is my client class:

package modelo;

public class Cliente {
Conta conta;
private int id;
private String nome;
private String sobrenome;
private String cpf;
private String rg;
private String endereco;



public Cliente(String nome, String sobrenome, String cpf,
        String rg, String endereco) {
    this.nome = nome;
    this.sobrenome = sobrenome;
    this.cpf = cpf;
    this.rg = rg;
    this.endereco = endereco;
}



public int getId() {
    return id;
}



public void setId(int id) {
    this.id = id;
}



public Cliente(){
}

public String getNome() {
    return nome;
}
public void setNome(String nome) {
    this.nome = nome;
}
public String getSobrenome() {
    return sobrenome;
}
public void setSobrenome(String sobrenome) {
    this.sobrenome = sobrenome;
}
public String getCpf() {
    return cpf;
}
public void setCpf(String cpf) {
    this.cpf = cpf;
}
public String getRg() {
    return rg;
}
public void setRg(String rg) {
    this.rg = rg;
}
public String getEndereco() {
    return endereco;
}
public void setEndereco(String endereco) {
    this.endereco = endereco;
}




}

And this is my clienteDAO :

package dao;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.SQLException;

import conexao.ConnectionFactory;
import modelo.Cliente;
import dao.ClienteDAO;

public class ClienteDAO {
Connection con;
PreparedStatement ps = null;
ResultSet rs;

public void cadastraCliente(Cliente cliente) {
    con = ConnectionFactory.getConnection();
    try {
        ps = con.prepareStatement("INSERT INTO cliente (nome, sobrenome, rg, cpf, endereco)" +
        "VALUES (?, ?, ?, ?, ?)");
        ps.setString(1, cliente.getNome());
        ps.setString(2, cliente.getSobrenome());
        ps.setString(3, cliente.getRg());
        ps.setString(4, cliente.getCpf());
        ps.setString(5, cliente.getEndereco());

        PreparedStatement ps2 = con.prepareStatement("SELECT idCliente FROM cliente WHERE nome LIKE '?' AND sobrenome "
            +   "LIKE '?' AND rg LIKE '?' AND cpf LIKE '?' AND  endereco LIKE '?'");
        ps2.setString(1, cliente.getNome());
        ps2.setString(2, cliente.getSobrenome());
        ps2.setString(3, cliente.getRg());
        ps2.setString(4, cliente.getCpf());
        ps2.setString(5, cliente.getEndereco());
        rs = ps2.executeQuery();
        cliente.setId(rs.getInt("idCliente"));

        ps.executeUpdate();
        ps.close();
        con.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }
}



public Cliente buscaCliente(String busca){
    con = ConnectionFactory.getConnection();
    try {
        PreparedStatement ps = con.prepareStatement("SELECT * FROM cliente WHERE nome LIKE '%?%' OR sobrenome "
            +   "LIKE '%?%' OR rg LIKE '%?%' OR cpf LIKE '%?%' OR  endereco LIKE '%?%'");
        ps.setString(1, busca);
        ps.setString(2, busca);
        ps.setString(3, busca);
        ps.setString(4, busca);
        ps.setString(5, busca);
        rs = ps.executeQuery();
        Cliente cliente = new Cliente();
            cliente.setNome(rs.getString("nome"));
            cliente.setSobrenome(rs.getString("sobrenome"));
            cliente.setRg(rs.getString("rg"));
            cliente.setCpf(rs.getString("cpf"));
            cliente.setEndereco(rs.getString("endereco"));
        ps.close();
        rs.close();
        con.close();
        return cliente;
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

public List<Cliente> listaClientes() {
    List<Cliente> clientes = new ArrayList<Cliente>();
    con = ConnectionFactory.getConnection();
    try {
        PreparedStatement ps = con.prepareStatement("SELECT * FROM cliente");
        rs = ps.executeQuery();
        Cliente cliente = new Cliente();
        while(rs.next()){
            cliente.setNome(rs.getString("nome"));
            cliente.setSobrenome(rs.getString("sobrenome"));
            cliente.setRg(rs.getString("rg"));
            cliente.setCpf(rs.getString("cpf"));
            cliente.setEndereco(rs.getString("endereco"));
            clientes.add(cliente);
        }
        ps.close();
        rs.close();
        con.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }

    return clientes;
}

public void atualizaDados(Cliente cliente, int id) {
    con = ConnectionFactory.getConnection();
    try {
        ps = con.prepareStatement("UPDATE banco.cliente SET nome = ?, sobrenome = ?, rg = ?, cpf =?, endereco = ? where idCliente = ?");
        ps.setString(1, cliente.getNome());
        ps.setString(2, cliente.getSobrenome());
        ps.setString(3, cliente.getRg());
        ps.setString(4, cliente.getCpf());
        ps.setString(5, cliente.getEndereco());
        ps.setInt(6, id);

        ps.executeUpdate();
        ps.close();
        con.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }

}

public void excluiCliente(String nome) {
    con = ConnectionFactory.getConnection();
    try {
        ps = con.prepareStatement("DELETE FROM cliente WHERE nome = ?");
        ps.setString(1, nome);

        ps.executeUpdate();
        ps.close();
        con.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }

}


public List<Cliente> ordenaLista(String coluna) {
    List<Cliente> clientes = new ArrayList<Cliente>();
    con = ConnectionFactory.getConnection();
    try {
        PreparedStatement ps = con.prepareStatement("SELECT * FROM cliente ORDER BY ?");
        ps.setString(1, coluna);
        rs = ps.executeQuery();
        Cliente cliente = new Cliente();
        while(rs.next()){
            cliente.setNome(rs.getString("nome"));
            cliente.setSobrenome(rs.getString("sobrenome"));
            cliente.setRg(rs.getString("rg"));
            cliente.setCpf(rs.getString("cpf"));
            cliente.setEndereco(rs.getString("endereco"));
            clientes.add(cliente);
        }
        ps.close();
        rs.close();
        con.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }

    return clientes;
}

public List<String> populaCombo(){
    List<String> nomes = new ArrayList<String>();
    try {
        con = ConnectionFactory.getConnection();
        PreparedStatement ps = con.prepareStatement("SELECT nome FROM cliente");
        rs = ps.executeQuery();
        while(rs.next()){
            nomes.add(rs.getString("nome"));
        }
        ps.close();
        rs.close();
        con.close();
        return nomes;           
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }

}


}

I've created a classe ContaCorrente and a ContaInvestimento that inherit from the Account and implement a interface ContaI . This is ContaCorrente :

package modelo;

public class ContaCorrente extends Conta {
double limite;

public ContaCorrente(){

}



public ContaCorrente(double saldo, double limite) {
    this.saldo = saldo;
    this.limite = limite;
}



public double getLimite() {
    return limite;
}

public void setLimite(double limite) {
    this.limite = limite;
}

@Override
public boolean deposita(double valor) {
    return super.deposita(valor);
}

@Override
public boolean saca(double valor) {
    if(valor > this.saldo + limite){
        System.out.println("Você não tem saldo suficiente para realizar esse saque");
    }
    System.out.println("Saque realizado com sucesso");
    return true;
}

@Override
public Cliente getDono() {
    return null;
}

@Override
public int getNumero() {
    return this.numero;
}

@Override
public double getSaldo() {
    return this.saldo;
}

@Override
public void remunera() {
    this.saldo *= 0.01;
}

}

And this is ContaInvestimento :

package modelo;

public class ContaInvestimento extends Conta{
double montanteMinimo;
double depositoMinimo;

public ContaInvestimento(){

}



public ContaInvestimento(double saldo, double montanteMinimo, double depositoMinimo) {
    this.saldo = saldo;
    this.montanteMinimo = montanteMinimo;
    this.depositoMinimo = depositoMinimo;
}



@Override
public boolean deposita(double valor) {
    if(valor >= depositoMinimo){
        super.deposita(valor);
    }
    return false;
}
@Override
public boolean saca(double valor) {
    return super.deposita(valor);
}
@Override
public Cliente getDono() {
    return null;
}
@Override
public int getNumero() {
    return this.numero;
}
@Override
public double getSaldo() {
    return this.saldo;
}
@Override
public void remunera() {
    this.saldo *= 0.01;
}
}

But I made a single contaDAO for the two classes :

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import conexao.ConnectionFactory;
import modelo.Cliente;
import modelo.ContaCorrente;
import modelo.ContaInvestimento;

public class ContaDAO {
Connection con;
PreparedStatement ps = null;
ResultSet rs;

public void criaContaCorrente(ContaCorrente conta){
    con = ConnectionFactory.getConnection();
    try {
        ps = con.prepareStatement("INSERT INTO conta (saldo) VALUES (?)");
        ps.setDouble(1, conta.getSaldo() + conta.getLimite());

        PreparedStatement ps2 = con.prepareStatement("SELECT idConta FROM conta WHERE idCliente = ?");
            ps.setInt(1,conta.getDono().getId());
            rs = ps2.executeQuery();
            conta.setNumero(rs.getInt("idConta"));

        ps.executeUpdate();
        ps.close();
        con.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

public void criaContaInvestimento(ContaInvestimento conta){
    con = ConnectionFactory.getConnection();
    try {
        ps = con.prepareStatement("INSERT INTO banco.conta (saldo) VALUES (?)");
        ps.setDouble(1, conta.getSaldo());

        ps.executeUpdate();
        ps.close();
        con.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

public boolean atualizaSaldo(double valor, int numero) {
    synchronized (this) {
        try {
            con = ConnectionFactory.getConnection();
            ps = con.prepareStatement("UPDATE conta SET saldo = ? WHERE idConta = ?");
            ps.setDouble(1, valor);
            ps.setInt(2, numero);
            return true;
        } catch (SQLException e) {
            return false;
        }
    }
}

public Cliente getDono() {
    return null;
}

public double getSaldo(int numero) {
    synchronized (this) {
        try {
            con = ConnectionFactory.getConnection();
            ps = con.prepareStatement("SELECT saldo WHERE idConta = ?");
            ps.setInt(1, numero);
            rs = ps.executeQuery();
            double saldo = rs.getDouble("saldo");
            return saldo;
        } catch (SQLException e) {
            System.out.println(e);
            return 0;
        }
    }
}

}

In my class VincularConta I have the following actionPerformed :

public void actionPerformed(ActionEvent e) {
    if(tipoConta.getSelectedItem().equals("Conta Corrente")){
        ContaDAO cd = new ContaDAO();
        ContaCorrente conta = new ContaCorrente(Double.parseDouble(depositoInicial.getText()),
                Double.parseDouble(limite.getText()));
        cd.criaContaCorrente(conta);
    }
    if(tipoConta.getSelectedItem().equals("Conta Investimento")){
        ContaDAO cd = new ContaDAO();
        ContaInvestimento conta = new ContaInvestimento(Double.parseDouble(depositoInicial2.getText()),
                Double.parseDouble(depositoMinimo.getText()), Double.parseDouble(montanteMinimoInput.getText()) );
        cd.criaContaInvestimento(conta);
    }
}

In my ClienteDAO I try to get the client id generated by bd and in my ContaDAO I try to use the id I got from the client to get the account id. But I can not even create the account, much less get the id. Can you help me understand what's wrong with my CRUD? Thank you in advance!

    
asked by anonymous 30.06.2016 / 00:35

1 answer

1

In order to be able to create any account whatsoever, since you have a% of client in the account, you must first create the client, have the client's Id , to finally register account.

It's very interesting what you're doing, I can advise a few things but it will depend a lot on the business rules of your software so that you can achieve a good implemented requirement.

First, in the foreign-key class, which is super-class of all other accounts, you must create a client object as class attribute. That way, from an account, you can know the customer.

Any insertion in the account bank you make will follow this order:

  • Have a client object, either existing (in the database) or not.
  • If it exists, it is not necessary to call the client DAO, since this client already has a Id setado
  • If it is not already existing, you must first include this client in the database and generate the Id of it.
  • Finally, always having a client with Id setado , you just set that client in the Account object, (% with% is it will either be whatever . Remember that when creating a client attribute in the super-class account, all other accounts will inherit this attribute.
  • Run the account DAO in the Id field of the client, you have already referenced the Id of the existing client.

It would look something like:

public abstract Conta {
//...
private Cliente cliente; //atributo de cliente em conta
//getters and setters
}

The most interesting of this approach is that this is the only association you need to be able to make your application work.

Let's say, for example, that you wanted to find out which accounts a given client has.

You should make a select in the account table by searching for the accounts that you have in the CustomerID field, the customer ID you are looking for.

You will always return zero, one or more accounts that have that client as client_id. So it is not necessary, for example, to create any other client account association (such as creating an Account List attribute within the client class)

I hope you have understood the concept. For any questions, I am available.

    
30.06.2016 / 01:04