通常来说,mybatis是使用xml映射进行操作数据库的,但是,在简单sql代码的情况下,也可以直接使用注解简化开发。
(工程上不建议使用,但是注解开发的思想比较重要)
例如,此时有pojo类User
1 2 3 4 5 6 7 8
| @Data @NoArgsConstructor· @AllArgsConstructor public class User { private int id; private String name; private String pwd; }
|
接口希望查询所有的User,返回一个User List
只需要在接口代码上面添加注解
1 2
| @Select("select * from user") List<User> getUsers();
|
这显然是非常简单的事情,但本文的重点其实不是此处的添加注解。
当基本数据类型作为参数传入时,按照规范,应该加param注解,如下所示
1 2 3
| // 方法存在多个参数,所有的参数前面必须加上 @Param("id")注解 @Select("select * from user where id = #{id}") User getUserByID(@Param("id") int id);
|
阿里巴巴规范中还规定,String类型的参数也应该加param注解。
那么,问题就来了,Param注解究竟有什么用,不加注解会出现什么状况?
先来测试一下上面提到的不加注解的情况
1 2
| @Select("select * from user where id = #{id}") User getUserByID(int id);
|

结果是可以正常打印
可以怀疑在#{}里面的东西实际上是没有任何意义的,甚至可以进行魔改
1 2
| @Select("select * from user where id = #{Java是世界上最好的语言}") User getUserByID(int id);
|
仍然可以正常打印
只有一个基本数据类型作为参数的时候,param是没有任何意义的。
但是多个参数就不一样了
1 2
| @Select("select * from user where id = #{id} and `name`=#{name}") User getUserByIDAndName(@Param("id") int id,@Param("name") String name);
|
只有这样才能正确打印出User
去掉注解就会出现以下错误
1 2 3
| org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [arg1, arg0, param1, param2] ### Cause: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [arg1, arg0, param1, param2]
|
总结:我们在SQL中引用的就是我们这里的 @Param() 中设定的属性名!
下面又来了个问题,在JDBC中,使用的是${},和这个#{}有啥区别吗?
- 简单来说,#{}更好,能有效防止sql注入攻击,尽量用#{}
但是注意:Mybatis的Order by 要用${}