您的位置:首页 > 移动开发

mybatis学习教程(五)mapper.xml篇

2015-09-07 09:54 375 查看


1、前言

这一篇主要讲mapper.xml的一些讲解。在项目开发中这些是主要编写的,例如UserMapper.xml,以及一些动态数据。


2、resultMap与resultType比较


resultType :指定输出结果的类型(pojo、简单类型、hashmap..),将sql查询结果映射为java对象。

使用resultType注意:sql查询的列名要和resultType指定pojo的属性名相同,指定相同 属性方可映射成功,如果sql查询的列名要和resultType指定pojo的属性
名全部不相同, list中无法创建pojo对象的

resultMap:将sql查询结果映射为java对象。如果sql查询列名和最终要映射的pojo的属性名不一致,使用resultMap将列名和pojo的属性名做一个对应关系 (列名和属性名映射配置)的


2.1
resultMap的使用

在项目开发中我们会经常用到resultMap,因为不可能你查询出来的结果就是需要的类型。例如你需要统计结果呢?count sum等等

1、首先我们写好mapper

UserMapper.xml红色字体

<span style="font-size:12px;font-weight: normal;"><?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">
<!--命名空间:分类管理sql隔离,方便管理-->
<mapper namespace="com.ycy.mybatis.dao.UserMapper">
    <!--定义个ResultMap-->
    <!--如果ResultMap定义在一个mapper.xml里面,直接使用resultMap的id ,如果不在同一个mapper要在resultMap前面加namespace-->
  <resultMap id="userResultMap" type="User">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="birthday" property="birthday"/>
        <result column="sex" property="sex" />
        <result column="address" property="address"/>
    </resultMap>
    <!--id标示一个sql语句,一个Statement,封装为一个MapperStatement-->
    <!--parameterType:传入参数类型;resultType:输出结果类型,指定映射的pojo-->
    <!--#{}标示一个占位符,-->
    <!--查询用户-->
    <!--oracle-->
    <!--   SELECT * FROM  USER  WHERE  username  LIKE  '%'||#{_parameter}||'%'-->
    <!-- mysql-->
    <select id="getUserById" parameterType="int" resultType="User">
         SELECT  * FROM USER WHERE id=#{id}
        </select>
    <select id="findUserByName" parameterType="com.ycy.mybatis.module.User" resultType="com.ycy.mybatis.module.User">
      SELECT * FROM  USER  WHERE  username  LIKE  '%${username}%'
    </select>
    <!--新增用户-->
    <insert id="insertUser" parameterType="User" >
        <!--插入值之后返回主键值-->
        <selectKey resultType="int" order="AFTER" keyProperty="id">
            SELECT LAST_INSERT_ID()
        </selectKey>
        INSERT  INTO USER  (username,birthday,sex,address) VALUES (#{username},#{birthday},#{sex},#{address})
    </insert>
    <!--删除用户-->
    <delete id="deleteUser" parameterType="int">
    DELETE  FROM USER  WHERE  id=#{id}
    </delete>
    <!--更新用户-->
    <update id="updateUser" parameterType="User">
        UPDATE USER  SET username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} WHERE id=#{id}
    </update>
    <select id="findUserResultMap" parameterType="user" resultMap="userResultMap">
    SELECT * FROM  USER
    <where>
        <include refid="query_user_where"/>
    </where>
</select>
    <!--sql查询片段-->
    <sql id="query_user_where" >
        <if test="username!=null and username!=''">
            AND  username  LIKE  '%${username}%'
        </if>
        <if test="sex!=null and sex!=''">
            AND  sex  =#{sex}
        </if>

    </sql>

</mapper></span>



2、写入mapper.java



UserMapper.java的红色字体

public interface UserMapper {
    public User getUserById(int id) throws Exception;
    public List<User> findUserByName(@Param("username") String username) throws Exception;
    public void  insertUser(User user) throws  Exception;
    public void deleteUser(int id)throws  Exception;
    public  void updateUser(User use) throws  Exception;
    <public List<User>  findUserResultMap(User user)throws Exception;</span>
}
3、测试

<span style="font-size:12px;">    /**
     * 查询用户使用ResultMap
     * @throws Exception
     */
    @Test
    public  void findUserResultMap() throws Exception {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        UserMapper userMapper=  sqlSession.getMapper(UserMapper.class);
        User user=new User();
        user.setUsername("小明");
        List<User> userList=  userMapper.findUserResultMap(user);
        sqlSession.close();
        for (User user1 : userList) {
            System.out.println(user1.getUsername());
        }
    }</span>



3、动态sql和sql片段(重点之重)

3.1动态sql

将自定义查询条件组合,达到动态sql,使得sql更加灵活。主要:本段紧接上面2中的xml,所以只展示部门代码。
where标签:自动去掉sql语句的第一个and,帅气吧。!
if标签:跟我们的jstl标签一样,判断你需要判断的事情。
以上标签都是配对出现,为什么你,因为xml文件就这么玩耍啊
<select id="findUserResultMap" parameterType="user" resultMap="userResultMap">
         SELECT * FROM  USER
          <where>
              <if test="username!=null and username!=''">
                  AND  username  LIKE  '%${username}%'
              </if>
              <if test="sex!=null and sex!=''">
                  AND  sex  =#{sex}
              </if>
          </where>
    </select>
3.2 sql片段
我sql片段就是把你经常用到的sql语句抽离出来,单独的为一段,这样你的臃肿的sql语句就更加简单,只需要加一个include标签,引入id。在不同的命名时候需要加命名空间,一般不建议垮命名空间(自己都找不到,虽然提供我还是不知道呀,你觉得呢(个人经验))。

<select id="findUserResultMap" parameterType="user" resultMap="userResultMap">
         SELECT * FROM  USER
          <where>
            <include refid="query_user_where"/>
          </where>
    </select>
    <!--sql查询片段-->
    <sql id="query_user_where" >
        <if test="username!=null and username!=''">
            AND  username  LIKE  '%${username}%'
        </if>
        <if test="sex!=null and sex!=''">
            AND  sex  =#{sex}
        </if>
    </sql>


3.3 for each语句

在statement通过foreach遍历parameterType中的集合类型。单独说,表名起重要性。

注意:此标签单独将,是为了引起注意,还有foreach标签必须使用在sql语句中

<!--foreach标签
        open:标示开始字符
        close:标示结束字符
        collection:标示list名字
        item:自定义名字
        separate:分隔符
        -->
        <foreach collection="ids" open="id in ( " close=" )" item="id" separator=",">
            #{id}
        </foreach>


到此:mybatis的基础篇讲完,完全你可以运用到你的项目,对于一个初级工程师已改没有什么阻碍。
如有疑问:qq群:78275755(目前木有人,来啦更好)

本项目1-5章 初级教程 项目百度分享盘: http://pan.baidu.com/s/1o63SUaI
Mybatis传多个参数(三种解决方案)(转载)

据我目前接触到的传多个参数的方案有三种。

第一种方案

DAO层的函数方法

1

Public User selectUser(String name,String area);

对应的Mapper.xml

1

2

3

<select id="selectUser" resultMap="BaseResultMap">

select * from user_user_t where user_name = #{0} and user_area=#{1}

</select>

其中,#{0}代表接收的是dao层中的第一个参数,#{1}代表dao层中第二参数,更多参数一致往后加即可。

第二种方案

此方法采用Map传多参数.

Dao层的函数方法

1

Public User selectUser(Map paramMap);

对应的Mapper.xml

1

2

3

<select id=" selectUser" resultMap="BaseResultMap">

select * from user_user_t where user_name = #{userName,jdbcType=VARCHAR} and user_area=#{userArea,jdbcType=VARCHAR}

</select>

Service层调用

1

2

3

4

5

Private User xxxSelectUser(){

Map paramMap=new hashMap();

paramMap.put(“userName”,”对应具体的参数值”);

paramMap.put(“userArea”,”对应具体的参数值”);

User user=xxx. selectUser(paramMap);}

个人认为此方法不够直观,见到接口方法不能直接的知道要传的参数是什么。

第三种方案

Dao层的函数方法

1

Public User selectUser(@param(“userName”)Stringname,@param(“userArea”)String area);

对应的Mapper.xml

1

2

3

<select id=" selectUser" resultMap="BaseResultMap">

select * from user_user_t where user_name = #{userName,jdbcType=VARCHAR} and user_area=#{userArea,jdbcType=VARCHAR}

</select>

个人觉得这种方法比较好,能让开发者看到dao层方法就知道该传什么样的参数,比较直观,个人推荐用此种方案。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: