MyBatis映射文件UserMapper.xml

本文介绍了MyBatis映射文件UserMapper.xml的使用,包括XML映射文件的主要元素,如cache、resultMap、insert、update、delete和select等。详细讲解了resultMap映射在字段名与属性名不同时的应用,以及insert语句的主键回写功能,查询、删除和修改语句的映射操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

XML映射文件

MyBatis 的真正强大在于它的映射语句,这是它的魔力所在。由于它的异常强大,映射器的 XML 文件就显得相对简单。如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近 95% 的代码。MyBatis 为聚焦于 SQL 而构建,以尽可能地为你减少麻烦。

SQL 映射文件只有很少的几个顶级元素(按照应被定义的顺序列出):

  • cache – 对给定命名空间的缓存配置。

  • cache-ref – 对其他命名空间缓存配置的引用。

  • resultMap –是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象

  • sql –可被其他语句引用的可重用语句块。

  • insert – 映射插入语句

  • update – 映射更新语句

  • delete – 映射删除语句

  • select – 映射查询语句

package com.gz.mapper;

import org.apache.ibatis.annotations.Param;

import com.gz.pojo.User;

public interface UserMapper {

	/**
	 * 新增用户
	 * @param user 需要添加的用户
	 * @return
	 */
	int insertUser(@Param("user") User user);
	
	/**
	 * 删除用户
	 * @param userId
	 * @return
	 */
	int deleteUser( int userId);
	/**
	 * 根据Id更新用户密码
	 * @param userId
	 * @return
	 */
	int updateUserPwdById(@Param("user")String name,Integer Id);
	/**
	 * 根据用户id查找用户
	 * @param id
	 * @return
	 */
	User findAllUserById(Integer id);
}

1、mapper配置xml文件和接口关联

1 <!--namespace务必和接口的全类名一致 -->
2 <mapper namespace="cn.bdqn.li.UserMapper">

2、resultMap映射。存在条件:当数据库字段名和实体类中的属性名不同的情况下。

1 <!--字段名和属性名不同时,使用resultMap映射-->
2     <resultMap id="userMap" type="User">
3         <id property="id" column="xsdm"/>
4         <result property="name" column="xsmc"/>
5     </resultMap>

3、insert into 添加语句(带主键回写)

<!--id务必和接口中的方法名称对应
    如果参数类型是一个对象,那么sql语句中#{对象的属性名}
         KeyProperty属性表示:   数据表主键对应的实体对象属性名称
         parameterType:要执行的dao中的方法的参数,如果是类的话,必须使用全路径类
        (全路径名可以使用在mybatis.xml文件中配置的别名代替)
-->
<!--新增用户的同时 拿到数据库中的id
 01.完成新增操作之后并没有把连接还给连接池
 02.而是接着使用连接去查询id
 SELECT @@IDENTITY
 SELECT LAST_INSERT_ID()   都可以获取刚刚插入数据的主键

  mysql中使用 order="AFTER", 主键自增,必须是插入数据成功之后才能获取id
  oracle中使用 order="BEFORE" ,必须先从序列中获取id,才能新增!

  useGeneratedKeys:  mybatis会根据数据库的不同获取主键===》 主键回填
 -->


    <insert id="addUser" parameterType="User"  keyProperty="id" useGeneratedKeys="true">
        insert into xs(xsmc)
        values(#{name})
         <!-- 回显,添加数据后,返回对象的id值 -->
        <selectKey resultType="int" keyProperty="id" order="AFTER">
            select @@IDENTITY
        </selectKey>
    </insert>

4、查询语句

<!--查询指定的user对象
            当数据库中的字段和实体类中的属性名相同时,使用resultType=“实体类名”。
        -->
    <select id="selectUserById" parameterType="int" resultType="User">
        SELECT  xsmc  from xs  where xsdm=#{id}
    </select>
    <!--查询指定的user对象
        当数据库中的字段和实体类中的属性名不相同时,使用resultMap=“上文写的resultMap的id名称”。
    -->
    <select id="selectUserById1" parameterType="int" resultMap="userMap">
        SELECT  xsmc  from xs  where xsdm=#{id}
    </select>

    <!--查询所有的用户信息-->
    <select id="selectAllUsers" resultMap="userMap">
        SELECT  xsdm,xsmc  from xs
    </select>

    <!--根据名称进行模糊查询-->
    <select id="selectByNamelike"  resultMap="userMap">
        SELECT  xsdm,xsmc  from xs
        WHERE   xsmc like concat('%',#{zzz},'%')
    </select>
    <!--多条件链接查询1(使用list集合)-->
    <select id="findUserByParams" resultMap="userMap">
        SELECT xsdm,xsmc from xs
        where xsmc LIKE concat('%',#{name},'%') AND xsdm >#{id}
    </select>
    <!--多条件链接查询2(使用Map集合)-->
    <select id="findUserByParams2" resultType="map">
        SELECT xsdm,xsmc from xs
        where xsmc LIKE concat('%',#{resultName},'%') AND xsdm >#{resultId}
    </select>
    <!--多条件链接查询3(使用索引)-->
    <select id="findUserByParams3" resultMap="userMap">
        SELECT xsdm,xsmc from xs
        where xsmc LIKE concat('%',#{0},'%') AND xsdm >#{1}
    </select>
    <!--if判断和where标签拼接-->
    <select id="selectAllUsersByIf" resultMap="userMap">
        select xsdm,xsmc from xs
        <where>
        <if test="name!=null and name!=''">
            and xsmc like concat('%',#{name},'%')
        </if>
            <if test="id!=null and id!=''">
              and xsdm>#{id}
            </if>
        </where>
    </select>
    <!--choose选择标签(和Java中的switch语句一样的效果)-->
    <select id="selectAllUserByChoose" resultMap="userMap">
        select xsdm,xsmc from xs
        <where>
        <choose>
            <when test="id>10">
                xsmc like concat('%',#{name},'%');
            </when>
            <when test="id>60">
                xsdm>30;
            </when>
            <otherwise>
                xsdm=1
            </otherwise>

        </choose>
        </where>
    </select>
    <!--foreach循环遍历数组-->
    <select id="selectAllUserByFor" resultMap="userMap">
        select * from xs
        <if test="array.length>0">
            where xsdm in
            <foreach collection="array" item="myid" open="(" separator="," close=")">
                #{myid}
            </foreach>
        </if>
    </select>
    <!--foreach循环遍历List-->
    <select id="selectAllUserByForList" resultMap="userMap">
        select * from xs
        <if test="list.size>0">
            where xsdm in
            <foreach collection="list" item="myid" open="(" separator="," close=")">
                #{myid}
            </foreach>
        </if>
    </select>
    <!--foreach循环遍历ArraryList集合-->
    <insert id="selectAllUserByForListUser" parameterType="java.util.ArrayList" >
        insert INTO xs(xsdm,xsmc) VALUES
        <if test="list.size>0">
            <foreach collection="list" item="user" separator="," index="index">
               (#{user.id},#{user.name})
            </foreach>
        </if>
    </insert>
    <!--foreach循环遍历Map集合-->
    <select id="selectAllUserByForMap" resultType="map">
        select * from xs
        <if test="map.keys.size>0">
            where xsdm in
            <foreach collection="map.values" item="user" open="(" separator="," close=")">
                #{user.id}
            </foreach>
        </if>
    </select>

5、删除语句

<!--删除功能  用户传递的是 一个变量! 这时候sql语句中的#{xxx}
      xxx只是一个占位符
      只有一个参数的时候,可以省略parameterType-->
    <delete id="deleteUser" parameterType="int">
        delete from xs where xsdm=#{xxx}
    </delete>

6、修改语句

<!--修改 用户传递的是 一个对象!这时候sql语句中的#{属性值}
      属性值必须和实体类中的属性一致 -->
    <update id="updateUser" parameterType="User">
        update   xs  set  xsmc=#{name}
        where xsdm=#{name}
    </update>
可以编写如下的UserMapper.xml文件: ```xml <!-- UserMapper.xml --> <mapper namespace="com.example.mapper.UserMapper"> <!-- 定义结果集映射 --> <resultMap id="userMap" type="com.example.model.User"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> <result property="age" column="t_age"/> </resultMap> <!-- 定义查询语句 --> <select id="selectAllUsers" resultMap="userMap"> select t_id, t_name, t_age from table2 </select> </mapper> ``` 在上述代码中,定义了一个命名空间为com.example.mapper.UserMapper映射文件。首先使用resultMap元素定义了一个名为userMap的结果集映射,指定了id、name、age成员变量分别对应表中的t_id、t_name、t_age字段。然后使用select元素定义了一个名为selectAllUsers的查询语句,指定了返回值类型为User类,使用了之前定义的userMap结果集映射,并指定了查询的表名和字段名。 在Java代码中,可以使用如下的方式调用该查询语句: ```java SqlSession sqlSession = ...; // 获取SqlSession对象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // 获取Mapper接口的实现对象 List<User> userList = userMapper.selectAllUsers(); // 调用查询方法 ``` 其中,UserMapper是一个Mapper接口,定义了一个名为selectAllUsers的查询方法,返回类型为List<User>,无参数。调用SqlSession的getMapper方法获取Mapper接口的实现对象,然后使用该对象调用selectAllUsers方法即可执行查询操作,并将结果封装为List<User>类型的对象返回。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值