如何将mapper方法执行后返回的多条数据存储到HashMap中并以该HashMap作为返回值?
时间: 2025-02-02 08:10:57 浏览: 75
要将mapper方法执行后返回的多条数据存储到HashMap中并以该HashMap作为返回值,可以按照以下步骤进行:
1. **创建Mapper接口**:首先,定义一个Mapper接口,并在其中定义一个方法用于查询数据。
```java
public interface MyMapper {
List<MyEntity> selectAll();
}
```
2. **创建实体类**:定义一个实体类,用于映射数据库中的表结构。
```java
public class MyEntity {
private Integer id;
private String name;
// Getters and Setters
}
```
3. **创建Service类**:在Service类中调用Mapper方法,并将返回的多条数据存储到HashMap中。
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class MyService {
@Autowired
private MyMapper myMapper;
public Map<Integer, String> getDataAsHashMap() {
List<MyEntity> entities = myMapper.selectAll();
Map<Integer, String> resultMap = new HashMap<>();
for (MyEntity entity : entities) {
resultMap.put(entity.getId(), entity.getName());
}
return resultMap;
}
}
```
4. **使用Service类**:最后,在需要的地方调用Service类的方法,获取存储在HashMap中的数据。
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/data")
public Map<Integer, String> getData() {
return myService.getDataAsHashMap();
}
}
```
这样,访问`/data`接口时,就会返回存储在HashMap中的数据。
阅读全文
相关推荐



















