Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added new selectMap method to get map with specified property as key and value #3235

Closed

Conversation

NiazBinSiraj
Copy link

Description:
A new selectMap() method has been added to SqlSession.java. This enhancement allows the conversion of a list of results into a Map, where the key is one specified property, and the value is another specified property from the resulting objects.

Background Story:
While working on a recent project in our company, I encountered a scenario where I needed to retrieve database results as a Map, with the key and value being specific column values. However, the current implementation of MyBatis does not support such a method. To address this, I’ve added the new selectMap() method, which I believe would be a valuable addition to the framework.

It will convert a list of results into a Map based on one of the properties as key and one of the properties as value in the resulting objects.
@harawata
Copy link
Member

harawata commented Sep 4, 2024

Thank you for the PR, @NiazBinSiraj !

Many people want this feature actually (e.g. #2672 #2865), however, it can easily be done using stream.

Map<Integer, String> map = mapper.selectAllAuthors().stream()
  .collect(Collectors.toMap(x-> x.getId(), x -> x.getUsername()));

You don't even need to define a custom class for this.

@Select("select * from author")
List<Map<String, Object>> selectMaps();
Map<Integer, String> map = mapper.selectMaps().stream()
  .collect(Collectors.toMap(e -> (Integer) e.get("id"), e -> (String) e.get("username")));

Also, for convenience, you can add a default method to the mapper interface.

default Map<Integer, String> getIdVsUsernameMap() {
  return selectMaps().stream()
    .collect(Collectors.toMap(e -> (Integer) e.get("id"), e -> (String) e.get("username")));
}

Although it requires one extra step, I think it's a better solution because it can handle more complex usages (and it does not require new methods in SqlSession).

I am going to close this as a duplicate.
Consider upvoting #2863 or #2865 if you still want to save the extra step.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants