<!-- User getUserByName(String name)--> <selectid="getUserByName"resultType="com.syh.bean.User"> select * from users where username = #{name} </select>
<!--User getUserByAgeAndGender(int age, char gender)--> <selectid="getUserByAgeAndGender"resultType="com.syh.bean.User"> select * from users where age = #{arg0} and gender = #{arg1} </select>
或者使用第二种方式的param1,param2:
1 2 3 4 5 6 7
<!--User getUserByAgeAndGender(int age, char gender)--> <selectid="getUserByAgeAndGender"resultType="com.syh.bean.User"> select * from users where age = #{param1} and gender = #{param2} </select>
<!--User getUserByMapInfo(Map<String, Object> info)--> <selectid="getUserByMapInfo"resultType="com.syh.bean.User"> select * from users where username = #{username} and age = #{age} </select>
<!--User getUserByUser(User user)--> <selectid="getUserByUser"resultType="com.syh.bean.User"> select * from users where username = #{username} and password = #{password} and age = #{age} and gender = #{gender} and email = #{email} </select>
User getUserByIdAndName(@Param("user_id")int id,@Param("user_name") String username);
在映射文件中,我们可以通过user_id和user_name来访问对应的内容:
1 2 3 4 5 6 7
<!--User getUserByIdAndName(@Param("user_id") int id,@Param("user_name") String username);--> <selectid="getUserByIdAndName"resultType="com.syh.bean.User"> select * from users where id = #{user_id} and username = #{user_name} </select>
<!-- User getUserByName(String name)--> <selectid="getUserByName"resultType="com.syh.bean.User"> select * from users where username = #{name} </select>
查询一个List集合
查询用户信息成为一个List集合:
1 2 3 4 5
<!-- List<User> getUserList()--> <selectid="getUserList"resultType="com.syh.bean.User"> select * from users </select>
查询单个数据
查询单个数据指的是查询得到一个int值或者其他字面量,例如这里查询用户的总数。
1 2 3 4 5
<!--int getSumOfUsers()--> <selectid="getSumOfUsers"resultType="int"> select count(*) from users </select>
<!--List<User> getUsersLike(@Param("likeStr") String likeStr)--> <selectid="getUsersLike"resultType="com.syh.bean.User"> select * from users where username like '%${likeStr}%' </select>
当然还有其他方式也能够完成对应操作:
1 2 3 4 5
select * from users where username like concat('%', #{likeStr}, '%') // 或者 select * from users where username like "%"#{likeStr}"%"
批量删除
在批量删除功能中,我们可以传入一个以逗号,分隔的id列表,然后直接拼接到括号当中,使用${}。
1 2 3 4
<!--int deleteBatch(@Param("ids") String ids)--> <deleteid="deleteBatch"> delete from users where id in (${ids}) </delete>
这里不能使用占位符,因为占位符会自动添加引号,导致格式错误。
动态设置表名称
动态设置表名称表示我们需要传入需要查询的表名称,这部分也是只能使用字符串拼接来完成的。
1 2 3 4
<!--List<User> getAllUserFrom(@Param("tableName") String tableName)--> <selectid="getAllUserFrom"resultType="com.syh.bean.User"> select * from ${tableName} </select>