// 4. 准备基本信息 // 4.1) statement: 用来定位映射文件(PersonMapper.xml)中的语句(通过namespace id + select id) //String statement = "com.xiya.dao.PersonDao.getPersonById"; // 4.2) parameter: 传进去的参数,也就是需要获取students表中主键值为1的记录 //int parameter = 1; // 5. SqlSession 实例来直接执行已映射的 SQL 语句,selectOne表示获取的是一条记录 //Person person = session.selectOne(statement, parameter); //System.out.println(person);这种方式是用SqlSession实例来直接执行已映射的SQL语句。
诚然这种方式能够正常工作,并且对于使用旧版本 MyBatis 的用户来说也比较熟悉,不过现在有了一种更直白的方式。
使用对于给定的sql语句能够合理描述其参数和返回值的接口(比如说PersonDao.class),你现在不但可以执行更清晰和类型安全的代码,而且还不用担心易错的字符串字面值以及强制类型转换。
PersonDao personMapper = session.getMapper(PersonDao.class); Person person = personMapper.getPersonById(1); System.out.println(person);PersonDao.java
package com.xiya.dao; import com.xiya.entity.Person; public interface PersonDao { Person getPersonById(int id); }
这里的getPersonById必须与PersonMapper.xml里的select id一致。
PersonMapper.xml里的命名空间需要指向PersonDao接口的全类名。
<?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"> <!-- namespace必须是唯一的,建议用该文件所在的包路径全类名 --> <mapper namespace="com.xiya.dao.PersonDao"> <!-- select:表示这是一个查询操作 --> <!-- id:用来配合namespace来定位这个操作,也就是在调用时,将采用com.xiya.entity.PersonMapper.getPerson --> <!-- resultType:表示返回值类型,必须是全类名,MyBatis将自动为我们将查询结果封装成 Person 对象 --> <!-- parameterType:表示传进来的参数的类型,因为传的是id主键,所以是int型 --> <select id="getPersonById" parameterType="int" resultType="com.xiya.entity.Person"> <!-- #{id}:表示占位符,也就是调用时必须为其传一个id参数进来,注意是#不是$ --> select * from persons where id = #{id} </select> <select id="getAllPersons" resultMap="persons"> select * from persons </select> <resultMap id="persons" type="com.xiya.entity.Person"> <result column="id" property="id"/> <result column="name" property="name"/> <result column="age" property="age"/> </resultMap> </mapper>
目录结构:
Demo:
https://github.com/N3verL4nd/MyBatis