publicinterfaceUserDao { //使用原生参数绑定 public User selectUserByIdAndPwd(Integer id , String pwd); }
1 2 3 4 5 6 7 8 9
<selectid="selectUserByIdAndPwd"resultType="user"> SELECT * FROM t_users WHERE id = #{arg0} AND password = #{arg1} <!--arg0 arg1 arg2 ...--> </select>
<selectid="selectUserByIdAndPwd"resultType="user"> SELECT * FROM t_users WHERE id = #{param1} AND password = #{param2} <!--param1 param2 param3 ...--> </select>
publicinterfaceUserDao { //使用 MyBatis 提供的 @Param 进行参数绑定 public User selectUserByIdAndPwd(@Param("id") Integer id , @Param("pwd") String pwd); }
1 2 3 4
<selectid="selectUserByIdAndPwd"resultType="user"> SELECT * FROM t_users WHERE id = #{id} AND password = #{pwd} <!-- 使用注解值 @Param("xxx") 中的 id或pwd --> </select>
1.1.3 Map参数绑定
1 2 3 4
publicinterfaceUserDao { //添加Map进行参数绑定 public User selectUserByIdAndPwd_map(Map values); }
<selectid="selectUserByIdAndPwd_map"resultType="user"> SELECT * FROM t_users WHERE id = #{myId} AND password = #{myPwd} <!-- 通过key获得value --> </select>
1.1.4 对象参数绑定
1 2 3 4
publicinterfaceUserDao { //使用对象属性进行参数绑定 public User selectUserByUserInfo(User user); }
1 2 3 4
<selectid="selectUserByUserInfo"resultType="user"> SELECT * FROM t_users WHERE id = #{id} AND password = #{password} <!-- #{id}取User对象的id属性值、#{password}同理 --> </select>
1.1.5 模糊查询
1 2 3
publicinterfaceUserDao { public List<User> selectUsersByKeyword(@Param("keyword") String keyword); }
1 2 3 4 5 6
<mappernamespace="com.mybatis.part1.different.UserDao"> <selectid="selectUsersByKeyword"resultType="user"> SELECT * FROM t_users WHERE name LIKE concat('%',#{keyword},'%') <!-- 拼接'%' --> </select> </mapper>
1.2 删除
标签:<delete id="" parameterType="">
1 2 3 4
<deleteid="deleteUser"parameterType="int"> DELETE FROM t_users WHERE id = #{id} <!--只有一个参数时,#{任意书写}--> </delete>
1.3 修改
标签:<update id="" parameterType="">
1 2 3 4
<updateid="updateUser"parameterType="user"> UPDATE t_users SET name=#{name}, password=#{password}, sex=#{sex}, birthday=#{birthday} WHERE id = #{id} <!--方法参数为对象时,可直接使用#{属性名}进行获取--> </update>
1.4 添加
标签:<insert id="" parameterType="">
1 2 3 4 5 6 7 8 9 10 11
<!--手动主键--> <insertid="insertUser"parameterType="user"> INSERT INTO t_users VALUES(#{id},#{name},#{password},#{sex},#{birthday},NULL); </insert>