In MyBatis & # {} {} and distinguish differences mybatis $ # {} {} and the

Original link: https://blog.csdn.net/qq_37776015/article/details/89931418

mybatis distinguish $ # {} and {a}

This section mainly on the difference mybatis $ # {} and {a}

 

First we see the difference between the two under through code examples:

There is such a method in EmployeeMapper interface:

Employee getEmpByIdAndLastName(@Param("id")Integer id, @Param("lastName") String lastName);

In the corresponding EmployeeMapper.xml mapping file sql syntax:

<select id="getEmpByIdAndLastName" resultType="employee">
    select id,last_name ,email,gender from tbl_employee where id = ${id} and last_name = #{lastName}
</select>

Test code:

public class MybatisTest {
    public SqlSessionFactory sessionFactory = null;
 
    @BeforeEach
    public void test()throws Exception{
    // 根据全局配置文件(xml)创建一个SqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }
 
    @Test
    public void selectTest(){
        // 获取 SqlSession 的实例 。SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。通过 SqlSession 实例来直接执行已映射的 SQL 语句
        SqlSession sqlSession = null;
        try {
            sqlSession = sessionFactory.openSession();
            // 通过获取接口代理对象来执行sql语句
            EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
            Employee employee = mapper.getEmpByIdAndLastName(2,"BB");
            System.out.println(employee.getLastName()); // AA
        } finally {
            // 资源关闭,放在finally中确保一定会执行
            sqlSession.close();
        }
    }
}

The final results of the implementation as follows:

DEBUG 05-07 22:52:42,700 ==>  Preparing: select id,last_name ,email,gender from tbl_employee where id = 2 and last_name = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-07 22:52:42,801 ==> Parameters: BB(String)  (BaseJdbcLogger.java:145) 
DEBUG 05-07 22:52:42,823 <==      Total: 1  (BaseJdbcLogger.java:145) 
BB

Note: sql statements in the log record is

select id,last_name ,email,gender from tbl_employee where id = 2 and last_name = ?   

Where $ {id} directly replaced by the incoming parameters, and # {lastName} is based on pre-compiled manner to become?

to sum up:

Same point:

  • # {}: Pojo value or value can be obtained in the map object property;
  • $ {}: Pojo value or value can be obtained in the map object property;


the difference:

  • # {}: Is pre-compiled form, set the parameter to the sql statement; the PreparedStatement; sql injection preventing
  • $ {}: Value taken directly assembled in the sql statement; poses security issues;

Note: In most cases, the value of the parameter should we go to use # {};
        

Use $ {} under what circumstances:

        Native jdbc does not support local placeholders we can use $ {} of value, such as column names, points table, sorting. .

// 按照年份分表
select * from ${year}_salary where xxx;
 
// 排序
select * from tbl_employee order by ${f_name} ${order}

………………………………………………

The following is the extension

# {} Richer usage

First, like other parts of MyBatis same parameter may specify a particular data type.

#{property,javaType=int,jdbcType=NUMERIC}

Like other parts of the same MyBatis, the javaType down almost always determined according to the type of the parameter object unless the object is a HashMap. This time, you need to explicitly specify the javaType to ensure that the correct type of processor (TypeHandler) is used.

JDBC requires prompt, if a column allows null values, and the parameters passed null value, it is necessary to specify the JDBC Type. Read PreparedStatement.setNull () the JavaDoc documentation for more information.

To further customize the type of treatment, you can specify a particular type of processor-based (or alias), such as:

#{age,javaType=int,jdbcType=NUMERIC,typeHandler=MyTypeHandler}
  
  

Although it looks complicated configuration becomes more and more, but in fact, rarely need such a complicated configuration.

For numeric types, there is provided a decimal digits reserved after the decimal point to specify the number of bits.

#{height,javaType=double,jdbcType=NUMERIC,numericScale=2}
  
  

Finally, mode attribute allows you to specify IN, OUT, or INOUT parameters. If the mode parameter is OUT or INOUT, just like you when specifying the output parameters desired behavior as the actual value of the property parameter object it will be changed. If the mode is OUT (or INOUT), and the jdbcType CURSOR (ie Oracle REFCURSOR), you must specify a resultMap reference to the result set ResultMap mapped to the type of the parameter. JavaType property to pay attention to here is optional, and if left blank jdbcType is CURSOR, it will be automatically set to ResultMap.

#{department, mode=OUT, jdbcType=CURSOR, javaType=ResultSet, resultMap=departmentResultMap}
  
  

MyBatis also supports more advanced data types such as structures (structs), but when using an out parameter, you must explicitly set the type of name. For example (again, in practice not do something like this to change):

#{middleInitial, mode=OUT, jdbcType=STRUCT, jdbcTypeName=MY_TYPE, resultMap=departmentResultMap}
  
  

While all of these options are very powerful, but most of the time you simply specify the property name, MyBatis other things on their own to infer, at most, to be designated as jdbcType may be empty columns.


  
  
  1. #{firstName}
  2. #{middleInitial,jdbcType=VARCHAR}
  3. #{lastName}

 

 

Guess you like

Origin blog.csdn.net/qq_44750696/article/details/101215859