<!-- 利用hashmap传递参数数据查询用户 --> <select id ="selectUserById4Map" parameterType="string" resultType="hashmap" > select <include refid ="allColumns" /> from user where id = #{id} </select> <!-- 利用hashmap传递参数数据插入用户信息 --> <select id ="insertUser4Map" parameterType="hashmap" > insert into user(id,name,age,address) values(#{id},#{name},#{age},#{address}) </select> <!-- 模糊查询 --> <select id ="selectUserByCondition3" parameterType="com.judy.mybatis.domain.User" resultType="com.judy.mybatis.domain.User" > select * from user where 1 = 1 <if test ="id!=null" > and id = #{id} </if> <if test ="name!=null" > and name like '%${name}%' </if> <if test ="age!=null" > and age = #{age} </if> <if test ="address!=null" > and address = #{address} </if> </select>
<!-- 利用动态sql语句更新user数据 --> <insert id ="updateUserByCondition" parameterType="com.judy.mybatis.domain.User" > update user <set> <if test ="name!=null" > name = #{name} </if> <if test ="age!=null" > age = #{age} </if> <if test ="address!=null" > address = #{address} </if> </set> where id=#{id} </insert> <!-- 动态seql语句查询用户 --> <select id ="selectUserByCondition" parameterType="com.judy.mybatis.domain.User" resultType="com.judy.mybatis.domain.User" > select * from user where 1 = 1 <if test ="id!=null" > and id = #{id} </if> <if test ="name!=null" > and name = #{name} </if> <if test ="age!=null" > and age = #{age} </if> <if test ="address!=null" > and address = #{address} </if> </select> <!-- 动态seql语句查询用户方式2 --> <!-- 这种方式会自动根据是否有id,如果有没有id,那么第一个条件将不加and --> <select id ="selectUserByCondition2" parameterType="com.judy.mybatis.domain.User" resultType="com.judy.mybatis.domain.User" > select * from user <where> <if test ="id!=null" > id = #{id} </if> <if test ="name!=null" > and name = #{name} </if> <if test ="age!=null" > and age = #{age} </if> <if test ="address!=null" > and address = #{address} </if> </where> </select>
<!-- 当字段很多的时候,可以通过下面这种方式抽取字段 --> <sql id ="allColumns" > id,name,age,address </sql> <!-- 如果在sqlMapConfig.xml中配置了别名,那么这里的resultType就可以直接写User --> <select id ="selectUserById" parameterType="string" resultMap="userMap" > select <include refid ="allColumns" /> from user where id = #{id} </select>