mybatis的sql占位符:#{}和${}


一、mybatis是对JDBC的封装,在JDBC中占位符使用的是?,在mybatis中占位符有两种形式,分别是#{}和${}

大多数情况下使用#{},少数需要使用${}

二、#{}和${}的区别在于,使用#{}占位符,当传递给sql 的参数替换占位符时会进行转译,如果传递的参数是字符串,在替换占位符时,会加上一对''号;而参数在替换${}时是直接拼接

三、当需要为不带引号的字符串进行占位时可以使用${}占位符

四、举例对比

根据字段name进行模糊查询

1、使用${}占位符

mapper.xml文件中:

<select id="findLike" resultType="com.qxzh.Emp">
select * from emp where name like '%${name}%'
</select>

java中:

    public static List<Emp> findLike(){
List<Emp> list =null;
try {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSession sqlSession = new SqlSessionFactoryBuilder().build(in).openSession();
//封装参数
// Emp emp=new Emp();
// emp.setName("刘");
// list = sqlSession.selectList("EmpMapper.findLike", emp);
       //或者:
HashMap<String, String> map = new HashMap<>();
map.put("name","陈");
list = sqlSession.selectList("EmpMapper.findLike", map);

} catch (IOException e) {
e.printStackTrace();
}
return list;
}

2、使用#{}占位符

mapper.xml中:

<select id="findLike2" resultType="com.qxzh.Emp">
select * from emp where name like #{name}
</select>

java中:

    public static List<Emp> findLike(){
List<Emp> list =null;
try {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSession sqlSession = new SqlSessionFactoryBuilder().build(in).openSession();
//封装参数
// Emp emp=new Emp();
// emp.setName("%刘%");
// list = sqlSession.selectList("EmpMapper.findLike2", emp);
       //或者
HashMap<String, String> map = new HashMap<>();
map.put("name","%陈%");
list = sqlSession.selectList("EmpMapper.findLike2", map);
} catch (IOException e) {
e.printStackTrace();
}
return list;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM