0
点赞
收藏
分享

微信扫一扫

Mybatis-查询结果返回一个Map

Mezereon 2022-04-05 阅读 52
后端java

一、返回一个字段名为键对应字段的值为值的Map
(1)Mapper文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wsh.mapper.UserMapper">
    <select id="selectUserMap" parameterType="Long" resultType="Map">
        select * from user where id = #{id}
    </select>
</mapper>

(2)接口文件

public interface UserMapper {
    public Map<String, Object> selectUserMap(Long id);
}

(3)JAVA文件

	public void test() throws IOException {
        //读取配置文件创建SqlSession工厂
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //利用SqlSession工厂创建SqlSession实例
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            //利用SqlSession创建代理对象
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //让代理对象帮我们执行查询
            Map<String, Object> mp = mapper.selectUserMap(1L);
            for (Map.Entry<String, Object> entry : mp.entrySet()) {
                System.out.println(entry.toString());
                /*
                password=123
				last_name=a
				id=1
                */
            }
        }finally {
            sqlSession.close();
        }
    }

(4)结果返回(键,值)=(字段名,字段对应的值)

二、返回一个字段的值为键对应结果对象为值的Map
(1)Mapper文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wsh.mapper.UserMapper">
    <select id="selectUserMap" resultType="User">
        select * from user
    </select>
</mapper>

(2)接口文件

public interface UserMapper {
    @MapKey("id")
    public Map<Long, User> selectUserMap();
}

(3)JAVA文件

	public void test() throws IOException {
        //读取配置文件创建SqlSession工厂
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //利用SqlSession工厂创建SqlSession实例
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            //利用SqlSession创建代理对象
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //让代理对象帮我们执行查询
            Map<Long, User> mp = mapper.selectUserMap();
            for (Map.Entry<Long, User> entry : mp.entrySet()) {
                System.out.println(entry.toString());
                /*
                1=User{id=1, lastName='a', password='123'}
				2=User{id=2, lastName='b', password='123'}
				3=User{id=3, lastName='c', password='123'}
                */
            }
        }finally {
            sqlSession.close();
        }
    }

(4)结果返回(键,值)=(字段的值,对应结果对象)

举报

相关推荐

0 条评论