Search code examples
javajdbcarraylistgeneric-programming

Java JDBC - From database to Arraylist<T>


I am looking for a more generic approach to add rows from a database to its corresponding model.

Where am i now...

I have multiple tables in a database with information about computerparts, ex. cpu(manufacturer, cores, speed ...), which I have added to an ArrayList<Cpu>. I construct the models by fetching the information from the database like so;

public ArrayList<Cpu> getAllCpu(ArrayList<Cpu> cpu, String sql) throws.. {

    ResultSet rs = queryGetResultSet("SELECT * FROM cpu");

    while(rs.next()){
        String manufacturer = rs.getString(1);
        String socket_type = rs.getString(2);
        // multiple lines, with string, integers and boolean types ...

        Cpu cpu = new Cpu(manufacturer, socket_type, ... );
        results.add(cpu);
    }

    return cpu;
}

Is there a neat way to avoid making multiple methods like this one, for my computerparts?

My end-goal would be to call something like the following;

ArrayList<Cpu> cpu = new ArrayList<>()
cpu = MyVeryIntelligentCode.getAll(cpu);

... and be able to get a list of all my cpu's in the database, and if I made a new table for McFlurry-types along with a model, I could use the same function to fetch an ArrayList for that!

Thanks in advance, you guys have helped me alot so far, but this time I had to ask a question myself!


Solution

  • Look at Spring jdbsTemplate queryForList

    https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html