国王陛下万万岁

导航

 

1. #:占位符,告诉mybatis使用实际的参数值代替。并使用PreparedSatement对象执行sql语句,#{...}代替sql语句的"?"。

这样更安全,更迅速,也是通常的做法。

mapper文件

<select id="selectOneAccountByNo" resultType="com.galaxy.bank.pojo.Account">
        select id, actno, balance, holder_name, country
        from bankdb.t_account
        where actno = #{actno}
    </select>

转化为myabtis的执行则是:

String sql="select id, actno, balance, holder_name, country from bankdb.t_account where actno =?"

PreparedStatement ps=conn.preparedStatement(sql);
ps.setInt(1,1005);

解释:

where id=?就是 where id=#{id}

ps.setInt(1,1005),1005会替换掉#{id}

 

2.$字符串替换符.

$告诉mybatis使用$当中包含的“字符串”替换所在位置。使用statement而不是PreparedStatement把sql语句和${}的内容连接起来。

主要在替换表名,列名,不同列排序等操作。

mapper文件:

 <select id="selectOneAccountByNo" resultType="com.galaxy.bank.pojo.Account">
        select id, actno, balance, holder_name, country
        from bankdb.t_account
        where actno =${actno}
    </select>

${}转化为SQL语句:

select id, actno, balance, holder_name, country from bankdb.t_account where actno =1005

而#{}转换为SQL语句则是:

select id, actno, balance, holder_name, country from bankdb.t_account where actno =?

假设mapper中的SQL语句如下:

select id, actno, balance, holder_name, country from bankdb.t_account where holder_name =${holder_name}

Java测试类调用Java的dao接口中的方法则该如下:

注意:双引号当中有单引号,如果没有单引号则会报错,因为${}是字符串替换。

List<Account> accounts=dao.selectAccountByDollar("'Tom Hanks'");

加上单引号,SQL语句才会变成:

select id, actno, balance, holder_name, country from bankdb.t_account where holder_name ='Tom Hanks';

 

3.$替换列名的操作

假设mapper中的SQL语句:

select id, actno, balance, holder_name, country from bankdb.t_account where balance>1000 order by ${myCountry}

 

Dao接口:

selectAccount$Order(@param("myCountry")String myCountry);

 

测试类:

List<Account> accounts=dao.selectAccount$Order("country);

转化为SQL语句为:

select id, actno, balance, holder_name, country from bankdb.t_account where balance>1000 order by country

注意:

  • 因为${}是字符串替换拼接,所以在到Dao接口中用@Param给参数去了个别名,但是这个别名对mapper无影响。
  •  ${}是用的Statement,而不是PreparedStatement,所以有SQL注入风险。

 

------------------------------------------------------------------------------------------------
2022年10月8日,农历九月十三,星期六,阴天有小雨,气温较冷,上海。
国庆节7天假期后的第一天,今日不调休,不上班.
-------------------------------------------------------------------------------------------------

 

posted on 2022-10-08 22:33  国王陛下万万岁  阅读(507)  评论(0编辑  收藏  举报