Mybatis配置文件之<mappers>配置元素解析

Mybatis配置文件之配置元素解析

mappers是mybatis的映射器,是mybatis中最复杂、最核心的功能组件,本文我们只是简单的介绍下映射器的引入,即在配置文件中的配置方式。
在mybatis中我们是通过映射器接口来调度我们的sql的,首先我们需要定义一个映射器接口,如下:

public interface UserMapper {
    /**
     * 查询
     * @param id
     * @return
     */
    User findUserById (long id);
    /**
     * 增加
     * @param user
     */
    void addUser(User user);
    /**
     * 删除
     * @param id
     */
    void deleteUser(long id);
    /**
     * 更新
     * @param user
     */
    void updateUser(User user);
}

然后再给出对应的XML文件,如下:

<?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.yhl.mybatis.mapper.UserMapper">

    <select id="findUserById" resultType="com.yhl.mybatis.model.User" parameterType="java.lang.Long" databaseId="mysql">
        select id,user_name as userName,age from t_user where id = #{id,jdbcType=BIGINT}
    </select>

    <insert id="addUser" parameterType="com.yhl.mybatis.model.User" useGeneratedKeys="true" keyProperty="id">
        insert into t_user(user_name,age) values(#{userName},#{age})
    </insert>

    <delete id="deleteUser" parameterType="java.lang.Long">
        delete from t_user where id = #{id,jdbcType=BIGINT}
    </delete>

    <update id="updateUser" parameterType="com.yhl.mybatis.model.User">
        update t_user set user_name = #{userName}, age = #{age} where id = #{id,jdbcType=BIGINT}
    </update>

</mapper>

接下来就是需要在配置文件中引入映射器了,引入方式有很多种,如下:
1. 用文件路径引入映射器,如下:

    <mappers>
        <mapper resource="com/yhl/mybatis/mapper/UserMapper.xml"/>
    </mappers>
  1. 用包名引入映射器,如下:
    <mappers>
        <package name="com.yhl.mybatis.mapper"/>
    </mappers>
  1. 用类注册引入映射器,如下:
    <mappers>
        <mapper class="com.yhl.mybatis.mapper.UserMapper"/>
    </mappers>
  1. 用相应的xml文件引入映射器,如下:
    <mappers>
        <mapper url="file:///var/com/yhl/mybatis/mapper/UserMapper.xml"/>
    </mappers>

猜你喜欢

转载自blog.csdn.net/uftjtt/article/details/80223218