简体   繁体   中英

How can I import data from a database with HashMap?

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM