接口映射文件(StudentMapper.java,也可归类为dao层)如下:
package com.java1234.mappers; import java.util.List; import com.java1234.model.Student; public interface StudentMapper { public int add(Student student); public int update(Student student); public int delete(Integer id); public Student findById(Integer id); public List<Student> find(); }
MyBatis映射文件解析如下:
<?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.java1234.mappers.StudentMapper"> <!-- resultMap用于定义返回结果集,里面定义了一个映射关系 --> <!-- type="Student"即集合的每个元素都是Student,id="StudentResult"为后面引用时使用 --> <resultMap type="Student" id="StudentResult"> <id property="id" column="id"/> <!-- id用来定义主键,实体Student中的属性id对应数据库表中的id字段--> <result property="name" column="name"/><!-- result用来定义普通属性,实体Student中的属性name对应数据库表中的name字段--> <result property="age" column="age"/> </resultMap> <!-- INSERT映射语句 --> <!-- id的名称必须与借口映射**mapper.java中的函数名称一致, parameterType为入参类型--> <!-- #{name} #{age} 为参数类中的字段或者是参数 --> <insert id="add" parameterType="Student" > insert into t_student values(null,#{name},#{age}) </insert> <!-- UPDATE映射语句 --> <update id="update" parameterType="Student"> update t_student set name=#{name},age=#{age} where id=#{id} </update> <!-- DELETE映射语句 --> <delete id="delete" parameterType="Integer"> delete from t_student where id=#{id} </delete> <!-- SELECT映射语句 --> <!-- resultType为返回类型,用到resultType必须在mybatis的配置文件中进行别名声明该resultType代表哪个实体类 --> <select id="findById" parameterType="Integer" resultType="Student"> select * from t_student where id=#{id} </select> <!-- resultMap代表返回一个结果集--> <select id="find" resultMap="StudentResult"> select * from t_student </select> </mapper>