Mybatis日志输出

  • 默认情况下,在Mybatis中,SQL语句执行时,我们并看不到SQL语句的执行日志。 在application.properties加入如下配置,即可查看日志:

    #mybatis的配置
    mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

增删改查操作

  • 在Mybatis中,我们可以通过参数占位符号 #{...} 来占位
  • Mybatis的提供的符号,有两个,一个是 #{...},另一个是 ${...},区别如下:

    符号说明场景优缺点
    #{…}占位符。执行时,会将#{…}替换为?,生成预编译SQL参数值传递安全、性能高 (推荐)
    ${…}拼接符。直接将参数拼接在SQL语句中,存在SQL注入问题表名、字段名动态设置时使用不安全、性能低
  • 如果在SQL语句中,我们需要传递多个参数,我们可以把多个参数封装到一个对象中。然后在SQL语句中,我们可以通过#{对象`属性`名}的方式,获取到对象中封装的属性值。

    • Mapper接口:
    /**
     * 添加用户
     */
    @Insert("insert into user(username,password,name,age) values(#{username},#{password},#{name},#{age})")
    public void insert(User user);
  • @param

    注解的作用是为接口的方法形参起名字的。

    • Mapper接口方法:
    /**
     * 根据用户名和密码查询用户信息
     */
    @Select("select * from user where username = #{username} and password = #{password}")
    public User findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);

    基于官方骨架创建的springboot项目中,接口编译时会保留方法形参名,@Param注解可以省略 (#{形参名})。