1

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?

1
  • can you post working sample of how ou fetched data from the data and returned a list<int>? Commented Jun 16, 2022 at 9:46

1 Answer 1

1

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[]> list = 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.

Sign up to request clarification or add additional context in comments.

1 Comment

I upvoted your answer but forgot to thank you, so thanks ! It worked perfectly for my case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.