mybatis 中如何取某个pojo类中的map中的值
时间: 2024-09-18 22:14:17 浏览: 59
在MyBatis中,如果你有一个POJO类(Plain Old Java Object)其中包含了Map类型的属性,当你从数据库查询结果中获取数据并映射到这个POJO上时,你需要明确指定如何处理Map的内容。假设你的POJO类结构如下:
```java
public class User {
private Map<String, Object> details;
// getters and setters...
}
```
当你编写SQL映射文件(Mapper XML 或者使用@Select注解)时,可以使用`resultType`或者`results`标签来指定返回的结果类型,并针对`details`字段设置动态属性,如下面的例子:
```xml
<select id="selectUser" resultType="com.example.User">
SELECT * FROM user WHERE id = #{id}
<include refid="userDetailsMap"/>
</select>
<sql id="userDetailsMap">
AND details.'key1' = #{key1}
<!-- 添加更多键值对,如果需要 -->
</sql>
```
或者使用Java配置的`ResultMap`:
```java
@Results({
@Result(property = "details", columnPrefix = "details.", javaType = Map.class, columnMapping = {
@Mapping(column = "key1", property = "details.key1"),
@Mapping(column = "key2", property = "details.key2")})
// 更多键值对映射
})
List<User> selectUsers(int id);
```
这样,当你通过`User`对象访问`details`时,就可以直接通过`user.getDetails().get("key1")`或者其他键名获取对应的值了。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)