1.resultType
上一篇中讲过可以自己封装任意的类型来作为PO对象,那么查询的时候,MyBatis返回结果会去mysql数据表中,或者sql语句的别名中查找列名。若找到了和resultType中任意一个属性相同的列名,则创建PO对象,将查找到的列名对应的值,赋值到resultType中对应的属性中。若找不到PO对象属性名和数据表中的列名对应的内容,则不会创建PO对象。2.resultMap
上面说到,通过resultType来组织查询结果时,如果找不到PO属性名对应的列名,则无法赋值。而resultMap则恰恰是处理当属性名和列名不一致时,该如何进行映射的一个配置。1).定义resultMap
2).使用resultMap作为statement的输出类型
如下面实例,SQL语句查询出来的列名都是带_开头的,而Student的名字不带_,为了实现查询结果映射到Student中,我们使用resultMap。
梁歪,下面定义的resultMap在其他的mapper文件中也可以使用,只需要加上namespace即可。 dao.StudentMapper.studentResultMap。
<?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="dao.StudentMapper">
<resultMap type="mybatis.Student" id="studentResultMap"> <!-- type是最终映射类型,id用来表示resultMap -->
<id column="_id" property="id"/> <!-- id是主键映射,若主键有多列组成,每一列都定义为一个id,result是普通列映射-->
<result column="_age" property="age"/>
<result column="_name" property="name"/>
</resultMap>
<select id="findStudentByName" parameterType="String" resultMap="studentResultMap">
select id _id, age _age, name _name from student where name = #{value}
</select>
</mapper>
3.parameterType为HashMap情况举例。
ForSQLPOMapper.xml,如下配置,将参数类型设置为HashMap,形参使用#{age}则实参会赋值为Map中age键的值。<?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="dao.ForSQLPOMapper">
<select id="findSQLPOByAge" parameterType="java.util.HashMap" resultType="mybatis.ForSQLPO">
select * from student where age = #{age}
</select>
</mapper>
映射接口代码。
public interface ForSQLPOMapper {
List<ForSQLPO> findSQLPOByAge(HashMap<String, Integer> age) throws Exception;
}
测试代码如下:
public static void main(String[] args) throws Exception {
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sessionFactory.openSession(true); //设置自动commit
HashMap<String, Integer>target = new HashMap<String, Integer>();
target.put("age", 11);
ForSQLPOMapper sqlMapper = session.getMapper(ForSQLPOMapper.class);
List<ForSQLPO> list = sqlMapper.findSQLPOByAge(target);
System.out.println(list);
}
4.select count(*)
1.sleect count的效率顺序 count(*) > count(主键) > count(非主键索引) > count(非主键非索引。
2.任何的Where条件都会降低Count(*)的效率,即使是WHERE 1=1。
3.select count(列名) 统计的个数不会计入NULL的值。
如果需要统计某列非NULL值的个数,则用count(列名),除此之外,建议都用Count(*)。
<完>