21、参数的传递

来源:互联网 发布:怎样变更淘宝店的地区 编辑:程序博客网 时间:2024/06/06 01:21

参数传递

mybatis的parameterType标签可以可定义传入的数据类型传入的类型分为以下几类
1. 基本数据类型(包括包装类型、String类型、Date类型)
2. List(Set)、Map
3. 实体类型

传入单个参数的示例

Dao层的方法

  Author selectByPrimaryKey(Integer id);

对应的mapper

    <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">        select        <include refid="Base_Column_List"/>        from author        where id = #{id,jdbcType=INTEGER}    </select>

传入到个参数

传入多个参数有三种

使用Map参数

Dao层的方法

 Author selectByPrimaryKey(Map<String,String> map);

Map的实际值map.put(“name”,”zhang”)
map.put(“id”,”1”)
对应的mapper

    <select id="selectByPrimaryKey" parameterType="Map" resultMap="BaseResultMap">        select        <include refid="Base_Column_List"/>        from author        where id = #{id,jdbcType=INTEGER}        where name = #{name,jdbcType=INTEGER}    </select>

按位置匹配

Dao层的方法

 Author selectByPrimaryKey(Integer id, String name);

对应的mapper

    <select id="selectByPrimaryKey"  resultMap="BaseResultMap">        select        <include refid="Base_Column_List"/>        from author        where id = #{0,jdbcType=INTEGER}        where name = #{1,jdbcType=INTEGER}    </select>

使用注解匹配

Dao层的方法

 Author selectByPrimaryKey(@Param("id") Integer id, @Param("name") String name);

对应的mapper

    <select id="selectByPrimaryKey"   resultMap="BaseResultMap">        select        <include refid="Base_Column_List"/>        from author        where id = #{id,jdbcType=INTEGER}        where name = #{name,jdbcType=INTEGER}    </select>

推荐用此种方案

使用对象传递参数

Dao层的方法

 Author selectByPrimaryKey(Author author);

对应的mapper

    <select id="selectByPrimaryKey"  parameterType="Author"  resultMap="BaseResultMap">        select        <include refid="Base_Column_List"/>        from author        where id = #{id,jdbcType=INTEGER}        where name = #{name,jdbcType=INTEGER}    </select>

Author对象里面包含有name字段和id字段

区别相同的参数名

如果dao层的方法中的参数有相同的时候
例如

 Author selectByPrimaryKey(@Param("author")Author author,@Param("name")String name);

假如Author也有名字为name的字段,如何使用Author对象中的name字段

```xml    <select id="selectByPrimaryKey"  parameterType="Author"  resultMap="BaseResultMap">        select        <include refid="Base_Column_List"/>        from author        where id = #{name,jdbcType=INTEGER}使用的是String类型的name字段        where name = #{author.name,jdbcType=INTEGER}使用的是author对象中的name字段    </select>

${}和#{}的区别


  1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by “111”, 如果传入的值是id,则解析成的sql为order by “id”.
  2. sqlorderbyuser_id$,如果传入的值是111,那么解析成sql时的值为order by user_id, 如果传入的值是id,则解析成的sql为order by id.
  3. #方式能够很大程度防止sql注入。
  4. $方式无法防止Sql注入。
  5. $方式一般用于传入数据库对象,例如传入表名.
  6. 一般能用#的就别用$.

MyBatis排序时使用order by 动态参数时需要注意,用$而不是#

原创粉丝点击