mybatis $和# 在解析 int类型和String类型的区别
[TOC]
测试代码如下
package com.dxhy.spike;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {DataSourceAutoConfiguration.class
, MybatisAutoConfiguration.class
, DataSourceTransactionManagerAutoConfiguration.class})
@MapperScan(basePackageClasses = {Inject.class})
public class MybatisInjectTest {
@Autowired
private Inject inject;
@Test
public void $queryByInteger() {
// 执行sql为 select id from base_email where create_by = 123
assertNotNull(inject.$query("123"));
}
@Test(expected = BadSqlGrammarException.class)
public void $queryByString() {
//执行sql 为 select id from base_email where create_by = system1
assertNotNull(inject.$query("system1"));
}
@Test
public void queryByInteger(){
/*
执行sql为
==> Preparing: select id from base_email where create_by = ?
==> Parameters: 123(String)
<== Total: 1
*/
assertNotNull(inject.query("123"));
}
@Test
public void queryByString(){
/*
执行sql为
==> Preparing: select id from base_email where create_by = ?
==> Parameters: system1(String)
<== Total: 1
*/
assertNotNull(inject.query("system1"));
}
}
@Mapper
interface Inject {
@Select("select id from base_email where create_by = ${param}")
String $query(@Param("param") String param);
@Select("select id from base_email where create_by = #{param}")
String query(@Param("param") String param);
}
可以看出$
的执行结果如下不和 #
不同,追一下源码,然后分析一下。
$
解析
DynamicSqlSource
(org.apache.ibatis.scripting.xmltags.DynamicSqlSource)中的getBoundSql
方法执行中,this.rootSqlNode.apply(context)
;这行代码开始就开始执行了解析sql的操作
- 其中
$
的解析为TextSqlNode
(org.apache.ibatis.scripting.xmltags.TextSqlNode)
3. 在 GenericTokenParser
(org.apache.ibatis.parsing.GenericTokenParser)的parse
中 直接将获取到的值进行toString之后和原sql 进行拼接。所以此处不会生成 "
和 '
。此处为 $queryByString
出现错误的原因。
![输入图片说明](https://static.oschina.net/uploads/img/201801/05193526_2ZP7.png "在这里输入图片标题")
#
解析
#
的解析发生在文件加载的过程中就已经完成了,并将#{}
替换为了?
号。 在最终请求中以参数完成了请求。所以没有受到请求参数类型的影响。