Bringing an Object to a ResultSet

0

I'm having trouble getting data from a Java search, I'm using PostgreSQL and JDBC database for persistence,

public List<Tapete> listarTapetes() {
    PreparedStatement state = null;
    ResultSet rs = null;
    try{
        String sql = "select * from Tapete order by preco";

        state = ConexaoPostgres.getConPostGres().prepareStatement(sql);

        rs = state.executeQuery();
        List<Tapete> listaTapetes = new ArrayList<Tapete>();
        while (rs.next()) {
            Tapete tapete = new Tapete(//DUVIDA);
            listaTapetes.add(tapete);
        }

        return listaTapetes;
    }

My problem is the following one where you have the comment (// DUVIDA). In my%% object, I have a variable of type Tapete and another of type Forma :

private Material material;
private Forma forma;

However, I can not do with what my Material brings me these objects, in my bank I defined material and shape as integers.

What should I do?

    
asked by anonymous 05.11.2014 / 23:52

2 answers

1

At each execution of rs.next() the cursor that "points" to the result brought by its SELECT goes down one line (contrary to what you may think it starts above the first line and not directly on the first line) . So after the first% w / o% it is on line 1, then on line 2, and so on until it returns rs.next() and therefore exits false , indicating that the lines are gone.

Its while object has methods that return the value of each column of the row where the cursor is currently positioned. See the ResultSet documentation and find out about its top methods, such as rs to bring a field INTEGER, getInt() to bring a CHAR or VARCHAR field, etc.

Note that these methods can be called by passing the table's column name or its column number as a parameter depending on the order the columns are in the database, for example getString() or getInt("material") . Choose the form you like best.

    
06.11.2014 / 00:25
1

I have done something similar to what you need to do, you will have the following classes:

  • Carpet.java
  • CarpetBD.java

My example is assuming that Material and Shape are also tables of your bank, in this case, they are foreign keys. In my example I'll put a NAME attribute for illustration only.

The Carpet.java class will be our bean, in it you will have only the attributes and their respective getters and setters, the Shape and Material classes will also need to have that same bean, and the same database class (assuming material and form are in the database).

class Tapete {
     private String nome;
     private Material material;
     private Forma forma;

     //getters and setters
}

In the CarpetBD class we will have a method similar to your ListTapetes (), let's call getTapetes () that will be responsible for the query and return the list.

class TapeteBD {
    //Métodos de conexão etc.

    private ResultSet rs = null; 
    private MaterialBD mbd = new MaterialBD(); //Criamos a classe que irá retornar o objeto Material.
    private FormaBD fbd = new FormaBD(); //Criamos a classe que irá retornar o objeto Forma.

   /* Essaes dois objetos, formaBD e MaterialBD serão responsáveis por chamar um método getMaterial() e getForma() respectivamente, já que o tapete recebe também dois objetos. */

public List<Tapete> getTapetes() throws SQLException {

    String sqlQuery = "SELECT * FROM Tapete ORDER BY preco";
    Tapete tapete = null; //Definimos o objeto tapete que terá seus atributos recuperados do banco de dados posteriormente.
    Material material = null; //Definimos o objeto material que será recuperado do banco de dados posteriormente.
    Forma forma = null; //Definimos o objeto forma que será recuperado do banco de dados posteriormente.
    List<Tapete> tapetes = new ArrayList<Tapete>;

    state = ConexaoPostgres.getConPostGres().prepareStatement(sql); //Essa parte da conexão eu não sei se está correta, pois não to com os arquivos aqui, só copiei o que você já tinha feito.
    rs = state.executeQuery();

    if(rs!=null) {
         rs.beforeFirst(); //Posiciona o cursos antes do primeiro elemento.
         while(rs.next()) {
             tapete = new Tapete(); //Criamos o tapete para setarmos os atributos de acordo com os dados recuperados do banco.
             tapete.setNome(rs.getString("nome"); //Setamos o nome de acordo com o recuperado do campo nome da tabela tapete no banco de dados.
             material = mbd.getMaterial(rs.getInt("codigo_material"); //Temos que ter uma classe de banco de dados para material para poder recuperar o objeto Material de acordo com sua chave estrangeira.
             forma = fbd.getForma(rs.getInt("codigo_forma");

             if(material != null) {
                  tapete.setMaterial(material); 
             }

             if(forma != null) {
                  tapete.setForma(forma);
             }

             tapetes.add(tapete); //Adicionamos o tapete com os atributos na lista.
         }
    }
return tapetes; //Retornamos a lista para o método que o chamou.
}

It's been a long time since I made this code, and I do not have it any more with me and I do not have IDE to test it here, there must be some errors, but at the most I think you can understand. Anything just ask. A hug.

EDITED

Had not read that you had defined Material and Shape as integers, these integers are foreign keys to another table? If they are the example it serves perfectly. You only have to create the classes:

  • Forma.java
  • FormaBD.java
  • Material.java
  • MaterialBD.java

With the structure a bit similar, I think with this you should know more or less how to proceed.

    
08.11.2014 / 21:35