How do I get foreign key values on a Jframe form

Asked

Viewed 1,481 times

0

I am creating a form in Jframe to insert data into a table that contains two foreign keys (since these keys are not generated automatically).

What I have to put on Insert to get foreign keys?

public void inserir(Tratamento tratamento) {
     try{
         try (Connection conexao = getConexao(); PreparedStatement stmt = conexao.prepareStatement("insert into tratamento "
                 + "(codigo_tratamento, titulo,  descricao) "
                 + "values (?,?,?)")) {
             stmt.setString(1, tratamento.getCodigo_tratamento());

             stmt.setString(2, tratamento.getTitulo());

             stmt.setString(3, tratamento.getDescricao());

             stmt.execute();
         }
    }catch(SQLException e){
    }
    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
  • I did not understand the question, do you want to fill two columns (which are foreign keys) of the treatment table? Or want to fetch the keys (sub-select) and fill in the Insert? You have something that identifies the two records of these relationships (Inner Join)?

  • Fetch keys and fill in the Insert.

  • What would be the ideal elements of Jframe to make the selection of the element?

1 answer

1

You can use a JComboBox. Where each item of ComboBox has a label and a value. The value you can use the id to facilitate the insert.

inserir a descrição da imagem aqui

To fill the JComboBox, suffice in the maker of JFrame load possible values through a select and then create the Items and add them to the ComboBox.

Being generic, the simplest would be something like:

List<Entidade> entidades = EntidadeDAO.buscar();
this.entidades = entidades; // Variável de instância da classe

JComboBox<Entidade> combo = new JComboBox<Entidade>();
this.combo = combo;

for(Entidade entidade : entidades) {
    combo.addItem(entidade); // Label que será exibida na tela vira do método toString()
}

Somewhere that performs the insertion action:

Entidade entidade = this.entidades.get(this.combo.getSelectedIndex());
// ou
Entidade entidade = this.combo.getSelectedItem();

Integer foreignKey = entidade.getId();
// Apartir dai você pode passar a chave estrangeira para a inserção da entidade tratamento.
this.tratamentoDAO.inserir(tratamento, foreignKey, ...);

This code was very generic, just adapt to your programming style. If you use MVC, there is the Listcellrenderer which helps to separate the logic of view of the logic of controller, never used, but may be useful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.