实现原理
Mapper接口开发只需要程序员编写Mapper接口(相当于DAO接口),由MyBatis框架根据接口定义创建接口的动态代理对象。MyBatis接口开发需要遵循以下规范:
- Mapper.xml文件中mapper标签的namespace属性值与 Mapper接口的类路径相同
- Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
- Mapper接口方法的输入参数类型和Mapper.xml中定义的每个sql的parameterType的类型相同
- Mapper接口方法的输出参数和Mapper.xml中定义的每个sql的resultType的类型相同
<?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="org.mybatis.demo.mapper.UserMapper">
<select id="findUserByUid" parameterType="java.lang.Integer" resultType="org.mybatis.demo.po.User">
select * from user where id = #{id}
</select>
<select id="findUserByUName" parameterType="java.lang.String" resultType="org.mybatis.demo.po.User">
select * from user where username like '%${value}%'
</select>
<!-- 新增并且返回递增主键 -->
<insert id="insertUser" parameterType="org.mybatis.demo.po.User">
<!--
selectkey:实现将主键返回
keyProperty:返回的主键储存在pojo中的哪个属性
order:selectkey的执行顺序,是相对于insert语句来说
resultType:返回的主键是什么类型
select LAST_INSERT_ID():函数是MySQL函数,返回auto_increament自增列新记录id值
-->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select LAST_INSERT_ID()
</selectKey>
insert into user(username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})
</insert>
<!-- 新增并且返回uuid主键 -->
<insert id="insertUserByUUID" parameterType="org.mybatis.demo.po.User">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.String">
select uuid()
</selectKey>
insert into user(username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})
</insert>
<delete id="deleteUserById" parameterType="java.lang.Integer">
delete from user where id=#{id}
</delete>
<update id="updateUserById" parameterType="org.mybatis.demo.po.User">
update user set username=#{username}, birthday=#{birthday}, sex=#{sex}, address=#{address} where id=#{id}
</update>
</mapper>
2、UserMapper接口
package org.mybatis.demo.mapper;
import org.mybatis.demo.po.User;
public interface UserMapper {
public User findUserByUid(int id);
public User findUserByUName(String name);
public int insertUser(User user);
}
注意:Mapper接口必须和Mapper.xml中mapper标签的namespace属性值的全类名一致,并且接口的方法名必须与Mapper.xml中定义的statement的id相同
3、源代码