batis查询

108 阅读1分钟

数据库属性名与类的属性名不同

映射

<mapper namespace="com.itheima.mapper.UserMapper">
    
        <!--
       id:完成主键字段的映射  
       result:完成一般字段的映射
         -->
           
    <resultMap id="userResultMap" type="user">
        <result column="user_name" property="username"/>
    </resultMap>
 
    <select id="selectAll" resultMap="userResultMap">
        select * from tb_user;
    </select>
        
</mapper>

条件查询

    List <User> selectByCondition(@Param("username") String username,@Param("gender") String gender);
        List<User> users1 = userMapper.selectByConditionSingle("张三","男");
//
    List <User> selectByCondition(User user);
        User user=new User();
        user.setGender("%男%");
        user.setUsername("%李%");
        List<User> users1 = userMapper.selectByConditionSingle(user);

动态条件查询

    <select id="selectByCondition" resultType="com.itheima.pojo.User">
        select * from tb_user 
        <where> 
             <if test="username!=null and username!=''">
               and username like #{username}  //前面都加and,<where>会自动适配
             </if> 
             <if test="gender!=null and gender!=''">
               and gender like #{gender}  
             </if>
           </where>;
    </select>
    <select id="selectByConditionSingle" resultType="com.itheima.pojo.User">
//相当于switch case Default
        select * from tb_user where
        <choose>
            <when test="username!=null and username!=''">
                username like #{username}
            </when>
            <when test="gender!=null and gender!=''">
                gender like #{gender}
            </when>
            <otherwise>
                1=1
            </otherwise>
        </choose>
    </select>