findStudentById”的 SQL 语句的,代码如下:
XML Code
<?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.aming.training.mybatis.mappers.StudentMapper"><resultMap type="Student" id="StudentResult"><id property="id" column="id" /><result property="name" column="name" /><result property="sex" column="sex" /><result property="birthday" column="birthday" /><result property="height" column="height" /><result property="weight" column="weight" /><result property="score" column="score" /><result property="address" column="address" /><result property="email" column="email" /><result property="hobby" column="hobby" /></resultMap><select id="findStudentById" parameterType="int" resultType="Student">SELECT id,name,email,birthday,height,weight,score,address,email,hobby FROM Student WHERE id = #{id}</select></mapper>
调用findStudentById映射的SQL语句
方法一:
@Test- public void testSelect() {
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();try{String mapper = "com.aming.training.mybatis.mappers.StudentMapper.findStudentById";int id = 1;Student student = sqlSession.selectOne(mapper,id);System.out.println(student);}finally{sqlSession.close();}}
我们可以通过字符串(字符串形式为:映射器配置文件所在的包名 namespace + 在文件内定义的语句 id,如上,即包
名 com.aming.training.mybatis.mappers.StudentMapper 和语句 id:findStudentById 组成)调用映射的 SQL 语句,但是这种方式
容易出错。你需要检查映射器配置文件中的定义,以保证你的输入参数类型和结果返回类型是有效的。
名 com.aming.training.mybatis.mappers.StudentMapper 和语句 id:findStudentById 组成)调用映射的 SQL 语句,但是这种方式
容易出错。你需要检查映射器配置文件中的定义,以保证你的输入参数类型和结果返回类型是有效的。
方法二:
第一步:创建一个映射器接口 StudentMapper.java
package com.aming.training.mybatis.mappers;import java.util.List;import com.aming.training.mybatis.pojo.Student;public interface StudentMapper {/*** 根据id获取Student对象* @param id id* @return Student对象*/Student findStudentById(int id);}
第二步:使用映射器接口我们可以以类型安全的形式调用调用映射语句
@Testpublic void testSelect2(){SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();try{int id = 1;StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);Student student = studentMapper.findStudentById(id);System.out.println(student);}finally{sqlSession.close();}}
说明:
1.在 StudentMapper.xml 映射器配置文件中,其名空间 namespace 应该跟 StudentMapper 接口的完全限定名保持一
致。另外, StudentMapper.xml 中语句 id, parameterType, returnType 应该分别和 StudentMapper 接口中的方法名,参数类型,返回值相对应。
2.即使映射器 Mapper 接口可以以类型安全的方式调用映射语句,但是我们也应该负责书写正确的,匹配方法名、参数类型、 和返回值的映射器 Mapper 接口。
如果映射器 Mapper 接口中的方法和 XML 中的映射语句不能匹配,会在运行期抛出一个异常。实际上,指定 parameterType 是可选的;MyBatis 可以使用反射机制来决定 parameterType。
但是,从配置可读性的角度来看,最好指定parameterType 属性。
如果 parameterType 没有被提及,开发者必须查看Mapper XML 配置和 Java 代码了解传递给语句的输入参数的数据类型。