本章节将介绍怎样使用 <select> 标签的 resultType 属性来指定返回结果类型,例如:统计总数量返回 Integer、数据行返回 HashMap(后面将介绍返回 JavaBean)。
(1)MyBatis 配置 mybatis-cfg.xml 文件如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="database.properties"/> <environments default="MySqlDatabase" > <environment id="MySqlDatabase" > <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <!-- 加载我们定义的Mapper文件 --> <mapper resource="com/hxstrive/mybatis/select/demo1/UserMapper.xml" /> </mappers> </configuration>
上面配置只是简单的配置了数据源和Mapper文件资源。
(2)Mapper 接口 UserMapper.java,如下:
package com.hxstrive.mybatis.select.demo1; import org.apache.ibatis.annotations.Param; import java.util.Map; public interface UserMapper { /** 根据ID查询用户信息 */ Map<String,Object> getUserById(@Param("userId") int userId); /** 查询用户数 */ int getUserCount(); }
(3)Mapper XML文件 UserMapper.xml,如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hxstrive.mybatis.select.demo1.UserMapper"> <!-- 根据ID查询用户信息 --> <select id="getUserById" parameterType="int" resultType="hashmap"> select `user_id`, `name`, `sex`, `age` from `user` where `user_id`=#{userId,jdbcType=INTEGER} </select> <!-- 查询用户数 --> <select id="getUserCount" resultType="integer"> select count(*) from `user` </select> </mapper>
(4)客户端,如下:
package com.hxstrive.mybatis.select.demo1; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; import java.util.Map; public class SelectDemo1 { public static void main(String[] args) throws Exception { String cfgName = "com/hxstrive/mybatis/select/demo1/mybatis-cfg.xml"; InputStream input = Resources.getResourceAsStream(cfgName); SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlFactory = factoryBuilder.build(input); SqlSession sqlSession = sqlFactory.openSession(true); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // 根据用户ID获取用户信息 Map<String,Object> userMap = userMapper.getUserById(1); for(String key : userMap.keySet()) { System.out.println(key + "=" + userMap.get(key)); } // 获取用户数量 int userCount = userMapper.getUserCount(); System.out.println("用户总数=" + userCount); } }
运行结果:
user_id=1 sex=男 name=张三 age=28 用户总数=2