假设1:我们现在需要通过账号和密码去查询数据库
分析:我们可以将这两个参数封装到Map集合中,通过Map集合去查询
@RequestMapping("/mybatis")
@Controller
public class MybatisController {
@Resource
private UserService userService;
@RequestMapping("/withTwoFields")
@ResponseBody
public User selectWithTwoFields(){
String username = "张三";
String password = "111111";
Map map = new HashMap();
map.put("username",username);
map.put("password",password);
return userService.selectWithTwoFields(map);
}
}
SQL语句
<!--Mybatis一次性传递多个参数-->
<select id="selectWithTwoFields" resultMap="BaseResultMap">
select * from user where user_name = #{username,jdbcType=VARCHAR} and user_password = #{password,jdbcType=VARCHAR};
</select>
查询结果如图:

假设2:我们现在需要通过多个参数去查询数据库,(账号、密码、性别……)
分析:接着上面的方法依然可行,但是不太方便。这时我们可以封装一个 Vo 类 ,通过这个Vo类的set方法来set值去查询。
@RequestMapping("/mybatis")
@Controller
public class MybatisController {
@Resource
private UserService userService;
@RequestMapping("/withMoreFields")
@ResponseBody
public User selectWithMoreFields(UserVo userVo){
userVo.setUsername("张三");
userVo.setPassword("111111");
userVo.setSex("男");
return userService.selectWithMoreFields(userVo);
}
}
<select id="selectWithMoreFields" parameterType="userVo" resultMap="BaseResultMap">
select * from user where user_name = #{username,jdbcType=VARCHAR} and user_password = #{password,jdbcType=VARCHAR};
</select>
查询结果如图:

假设3:还是刚刚的条件
分析:我们还可以通过 @param 注解的方式去查询
Controller层代码:
@RequestMapping("/mybatis")
@Controller
public class MybatisController {
@Resource
private UserService userService;
@RequestMapping("/withParam")
@ResponseBody
public User selectWithParam(){
String username = "张三";
String password = "111111";
return userService.selectWithParam(username,password);
}
}
Dao层代码:
User selectWithParam(@Param("userName") String username, @Param("passWord") String password);
SQL语句:
<select id="selectWithParam" resultMap="BaseResultMap">
select * from user where user_name = #{userName,jdbcType=VARCHAR} and user_password = #{passWord,jdbcType=VARCHAR};
</select>
需要注意的点:SQL语句中的 userName 是和 @Param(“userName”) 相呼应的,注意看大小写……
本文探讨了三种方法:封装Map查询、Vo对象查询和使用@Param注解,对比在Mybatis中通过不同参数传递方式实现数据库查询的灵活性和效率。从单字段到多字段,再到参数化的例子,展示了如何优化数据库操作并提高代码可维护性。

1万+

被折叠的 条评论
为什么被折叠?



