Home > Software engineering >  How can I import data from a database with HashMap?
How can I import data from a database with HashMap?

Time:06-22

I need to import data from a database with hashmap. There is a table media and I need to get the media_id (integer) and media_path (String). Before this, I was only importing the media id like this:

private List<Integer> getMedias() {
    final String queryString = "SELECT media_id from media where XXX ..."

    final Query query = App.getCurrentSession().createSQLQuery(String.valueOf(queryString));
    query.setString("xxx", xxx);
    query.setDate("xxx", xxx);
    query.setDate("xxx", xxx);

    return query.list();

Now, I want to do something more like this:

private HashMap<Integer, String> getMedias() {
    final String queryString = "SELECT media_id, media_path from media where XXX ..."

The problem is that I don't know how to do with the SQL query in order to get a hashmap from the database.

How can I do that?

CodePudding user response:

I don't think there's a way to do it out of the box. You need to convert the result:

List<Object[]> queryResults = query.list();
Map<Integer, String> resultAsMap = new HashMap<>();
for(Object[] row : queryResults) {
   resultAsMap.put((Integer)row[0], (String)row[1]);
}
return resultAsMap;

Or you can use streams:

List<Object[]> queryResults = query.list();
Map<Integer, String> resultAsMap = list
    .stream()
    .collect( Collectors.toMap( row -> (Integer) row[0], row -> (String) row[1] ) );
return resultAsMap;

Alternatively, you could return a list of DTOs using a ResultTransformer.

  • Related