Mybatis的#与$问题

#:占位符,告诉 mybatis 使用实际的参数值代替。并使用 PrepareStatement 对象执行 sql 语句, #{…}代替
sql 语句的“?”。这样做更安全,更迅速,通常也是首选做法,
mapper 文件
<select id="selectById" resultType="com.bjpowernode.domain.Student">
 select id,name,email,age from student where id=#{studentId}
</select>
转为 MyBatis 的执行是:
String sql=” select id,name,email,age from student where id=?”;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,1005);
解释:
where id=? 就是 where id=#{studentId}
ps.setInt(1,1005) , 1005 会替换掉 #{studentId}
$ 字符串替换,告诉 mybatis 使用$包含的“字符串”替换所在位置。使用 Statement 把 sql 语句和${}的
内容连接起来。主要用在替换表名,列名,不同列排序等操作。
mapper 文件:
<select id="findById" resultType="com.bjpowernode.domain.Student">
 select * from student where id=#{studentId}
</select> <select id="findByEmail" resultType="com.bjpowernode.domain.Student">
 select * from student where email=#{stuentEmail}
</select>
@Test
public void testFindStuent(){
 Student student1 = studentDao.findById(1002);
 System.out.println("findById:"+student1);
 Student student2 = studentDao.findByEmail("zhou@126.net");
 System.out.println("findByEmail:"+student2);
}
通用方法,使用不同列作为查询条件
接口方法:
Student findByDiffField(@Param("col") String colunName,@Param("cval") Object
value);
mapper 文件:
<select id="findByDiffField" resultType="com.bjpowernode.domain.Student">
 select * from student where ${col} = #{cval}
</select>
@Test
public void testFindDiffField(){
 Student student1 = studentDao.findByDiffField("id",1002);
 System.out.println("按 id 列查询:"+student1);
 Student student2 = studentDao.findByDiffField("email","zhou@126.net");
 System.out.println("按 email 列查询:"+student2);
}

 

posted @ 2021-09-18 11:28  好吗,好  阅读(408)  评论(0)    收藏  举报