MyBatis (5) parameter passing

1. Single parameter:

  The parameters in the method are the parameters in the SQL statement. Because there is only one parameter, it can be executed normally even if the parameter names are not uniform.

2. Multiple parameters:

  mybatis will do special processing to encapsulate multiple parameters into a map.

  • key:param1,param2…paramN
  • value: the incoming value
  • #{} is to get the specified key value from the map

operate:

  1. 方法:public Employee getEmployeeByIdAndName(Integer id,String lastName);
  2. 取值:select * from employee where id = #{param1} and last_name = #{param2}

3. Named parameters:

The key of map when explicitly specifying encapsulation parameters: @Param("id)

Multiple parameters will still be encapsulated into a map:

  • key: use the value specified by the annotation @Param
  • value: the incoming parameter value

operate:

  1. 方法:public Employee getEmployeeByIdAndName(@Param(“id”)Integer id,@Param(“lastName”)String lastName)
  2. 取值:select * from employee where id = #{id} and last_name = #{lastName}

4.POJO :

  • If multiple parameters correspond to the data model of our business logic, we can directly pass in pojo;
  • #{attribute name}: Take out the attribute value of pojo

Map:
If multiple parameters are not data in the business model and are not often used, for convenience, we can pass in a map;
#{key}: Get the value in the map

The difference between # and $ value:

#{}: You can take out the parameter value or the attribute value of the pojo.

${}: You can take out the parameter value or the attribute value of the pojo.

the difference:

  • #{}: Set parameters into sql in precompiled form; PreparedStatement to prevent sql injection.
  • ${}: The retrieved value is directly spliced ​​into the sql statement, which will cause security problems.

In general, to get the value of a parameter, you should use #{}

Where native jdbc does not support placeholders, you can use ${}:

比如分表:按照年份分表查询

    select * from ${year}_salary where xxx;

按照某个字段排序:

    select * from tb_eamployee order by ${name} ${order}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324606984&siteId=291194637