重学Mybatis从入门到源码之三---一个CRUD以及模糊查询

写一个CRUD,这个比较简单,只需要强调一点:增删查之后要对sqlSession进行commit操作,不然不能生效!

    @Test
    public void updateUser() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.updateUser(new User(6, "candice6", "candice"));
        sqlSession.commit();
        sqlSession.close();
    }
    <update id="updateUser" parameterType="com.candice.pojo.User">
        update user set name = #{name}, pwd = #{pwd} where id = #{id}
    </update>

模糊查询:

我们都知道在sql中模糊查询就是like %name%,那么在Mybatis中应该要怎么写?

1. 使用#{...}

 可以使用。注意:因为#{...}解析成sql语句时候,会在变量外侧自动加单引号'  ',所以这里 % 需要使用双引号"  ",不能使用单引号 '  ',不然会查不到任何结果。

2. 使用CONCAT()函数连接参数形式 concat('%', #{name}, '%')

然后 #{} 和 ${} 的区别:

1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by "111", 如果传入的值是id,则解析成的sql为order by "id".
  
2. $将传入的数据直接显示生成在sql中。如:order by $user_id$,如果传入的值是111,那么解析成sql时的值为order by user_id,  如果传入的值是id,则解析成的sql为order by id.
  
一般能用#的就别用$.

所以#方式能够很大程度防止sql注入,$方式无法防止Sql注入。

使用$场景:

1. MyBatis排序时使用order by 动态参数时需要注意,用$而不是#,

2.$方式一般用于传入数据库对象,例如传入表名.

原文地址:https://www.cnblogs.com/yunyunde/p/13820368.html