Yesterday, I was asked such a question in the phone interview. The fact is that I just used it, and I don't know it. Unfortunately, I missed it (in fact, it was wiped out because of multi-threading)
1. # Treat the incoming data as a string , and add a double quote to the automatically incoming data
For example: order by #user_id#, if the incoming value is 111, then the value when parsed into sql is order by "111", if the incoming value is id, the parsed sql is order by "id"
2. $ Display the incoming data directly and generate it in sql
For example: order by $user_id$, if the incoming value is 111, then the value when parsed into sql is order by 111, if the incoming value is id, the parsed sql is order by id
3. #The method can prevent sql injection to a large extent
4. The $ method cannot prevent Sql injection
5. The $ method is generally used to pass in database objects, such as incoming table names
6. If you can use #, don’t use $. When using order by dynamic parameters in MyBatis sorting, you need to pay attention to using $ instead of #
See an example, this is a method to query all data
@ResponseBody @RequestMapping("findByPage") public PageView findByPage( String pageNow, String pageSize,String column,String sort) throws Exception { UserFormMap userFormMap = getFormMap(UserFormMap.class); userFormMap=toFormMap(userFormMap, pageNow, pageSize,userFormMap.getStr("orderby")); userFormMap.put("column", column); userFormMap.put("sort", sort); pageView.setRecords(userMapper.findUserPage(userFormMap)); return pageView; }
mapper.xml, I still use $
<select id="findUserPage" resultType="com.dingshu.entity.UserFormMap"> select <include refid="selectId" /> from ds_user where 1 = 1 <if test="accountName != null and accountName != ''"> and accountName like '%${accountName}%' </if> <if test="column != null"> order by ${column} ${sort} </if> </select>