天天看點

Mybatis學習筆記6 - #{}和${}

#{}:可以擷取map中的值或者pojo對象屬性的值。

${}:可以擷取map中的值或者pojo對象屬性的值。

差別:

  #{}:是以預編譯的形式,将參數設定到sql語句中;PreparedStatement;防止sql注入

  ${}:取出的值直接拼裝在sql語句中;會有安全問題;

  大多情況下,我們去參數的值都應該去使用#{};

select * from tbl_employee where id=${id} and last_name=#{lastName}

Preparing: select * from tbl_employee where id=2 and last_name=?

${}的使用:原生jdbc不支援占位符的地方就可以使用${}進行取值

      比如分表(按照年份分表拆分)、排序等

      select * from ${year}_salary where xxx;

      select * from tbl_employee order by ${f_name} ${order}

${}使用示例:

接口定義:
package com.mybatis.dao;

import com.mybatis.bean.Employee;

import java.util.Map;

public interface EmployeeMapper {
    public Employee getEmpByIdAndLastName(Map<String, Object> map);
}

mapper定義:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.dao.EmployeeMapper">
    <select id="getEmpByIdAndLastName" parameterType="java.util.Map" resultType="com.mybatis.bean.Employee">
        select * from ${tableName} where id=${id} and last_name=#{lastName}
    </select>
</mapper>

測試代碼:
package com.mybatis.demo;

import java.io.*;
import java.util.*;

import com.mybatis.bean.Employee;
import com.mybatis.dao.EmployeeMapper;
import org.apache.ibatis.io.*;
import org.apache.ibatis.session.*;
import org.junit.Test;

public class MyTest {
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void testSelect() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession(true);
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", 5);
            map.put("lastName", "jetty");
            map.put("tableName", "tbl_employee");
            Employee employee = mapper.getEmpByIdAndLastName(map);
            System.out.println(employee);
        } finally {
            openSession.close();
        }
    }
}