MyBatis深入理解參數


一、快速創建mapper文件

由於每個接口都要創建一個對應的mapper文件,這個文件在IDEA中創建中沒有提示,而且這個文件的整體都是一樣的,所以創建一個模板,方便使用

把自己感覺常用的代碼添加進去,然后自定義名稱,以及擴展名

這樣下次創建的時候就方便很多

模板:

<?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="">
    <select id="" resultType="">
    </select>
</mapper>

當然也可以設置主配置文件,方法和上面的類似

二、parameterType

dao接口中方法參數的數據類型
值為java的數據類型全限定名稱或者是mybatis定義的別名
例:parameterType="java.lang.Integer",或者 parameterType="int"
注意:這個一般不寫,因為mybatis通過反射機制能夠發現接口參數的數據類型

例如:

    <select id="selectStudentById" resultType="com.md.domain.Student" parameterType="java.lang.Integer">
      select id , name , email , age from student where id=#{id}
    </select>
<!--等同於-->
    <select id="selectStudentById" resultType="com.md.domain.Student" parameterType="int">
      select id , name , email , age from student where id=#{id}
    </select>

三、MyBatis 傳遞參數

1. 一個簡單參數(掌握)

Dao 接口中方法的參數只有一個簡單類型(java 基本類型和 String),

占位符 #{ 任意 字符 },和方法的參數名無關

接口方法:

Student selectById(int id);

mapper文件

<select id="selectById" resultType="com.md.domain.Student">
select id,name,email,age from student where id=#{studentId}
</select>

#{studentId} , studentId 是自定義的變量名稱,和方法參數名無關

注意:

使用#{}之后, mybatis執行sql是使用的jdbc中的PreparedStatement對象
由mybatis執行下面的代碼:

1. mybatis創建Connection , PreparedStatement對象
            String sql="select id,name, email,age from student where id=?";
            PreparedStatement pst = conn.preparedStatement(sql);
            pst.setInt(1,1001);

2. 執行sql封裝為resultType="com.md.domain.Student"這個對象
            ResultSet rs = ps.executeQuery();
            Student student = null;
            while(rs.next()){
               //從數據庫取表的一行數據, 存到一個java對象屬性中
               student = new Student();
               student.setId(rs.getInt("id"));
               student.setName(rs.getString("name"));
               student.setEmail(rs.getString("email"));
               student.setAge(rs.getInt("age"));
            }

           return student;  //給了dao方法調用的返回值

測試方法

@Test
public void testSelectById(){
// 一個參數
Student student = studentDao.selectById(1001);
System.out.println(" 查詢 id 是 1001 的學生:"+student);
}

2. 多個參數- 使用@Param(掌握)

當 Dao 接口方法多個參數,需要通過名稱使用參數。

在方法形參前面加入@Param(“自定義參數名”),mapper 文件使用#{自定義參數名}。

接口方法

List<Student> selectMultiParam(@Param("personName") String name,
@Param("personAge") int age);

mapper文件

<select id="selectMultiParam" resultType="com.md.domain.Student">
select id,name,email,age from student where name=#{personName} or age
=#{personAge}
</select>

測試方法

@Test
public void testSelectMultiParam(){
List<Student> stuList = studentDao.selectMultiParam("李白",20);
stuList.forEach( stu -> System.out.println(stu));
}

3. 多個參數-使用對象(掌握)

使用 java 對象傳遞參數, java 的屬性值就是 sql 需要的參數值。

每一個屬性就是一個參數。

常用格式 #{ property }

1. 創建保存參數值的對象 QueryParam

package com.md.vo;
    public class QueryParam {
    private String queryName;
    private int queryAge;
    //set , get 方法 有參無參
}

2. 接口方法:

List<Student> selectMultiObject(QueryParam queryParam);

3. mapper文件

<select id="selectMultiObject" resultType="com.md.domain.Student">
select id,name,email,age from student where name=#{queryName} or age
=#{queryAge}
</select>

4. 測試方法

@Test
public void selectMultiObject(){
    QueryParam qp = new QueryParam();
    qp.setQueryName("白昊天");
    qp.setQueryAge(20);
    List<Student> stuList = studentDao.selectMultiObject(qp);
    stuList.forEach( stu -> System.out.println(stu));
}

4. 多個參數-按位置(了解)

參數位置從 0 開始, 引用參數語法 #{ arg 位置 } , 第一個參數是#{arg0}, 第二個是#{arg1}
注意:mybatis-3.3 版本和之前的版本使用#{0},#{1}方式, 從 mybatis3.4 開始使用#{arg0}方式。
接口方法:

List<Student> selectByNameAndAge(String name,int age);

mapper 文件

<select id="selectByNameAndAge" resultType="com.md.domain.Student">

select id,name,email,age from student where name=#{arg0} or age =#{arg1}

</select>

測試方法:

@Test

public void testSelectByNameAndAge(){

// 按位置參數

List<Student> stuList = studentDao.selectByNameAndAge(" 李白",20);

stuList.forEach( stu -> System.out.println(stu));

}

5. 多個參數- 使用 Map(了解)

Map集合可以存儲多個值,使用Map向mapper文件一次傳入多個參數。Map集合使用String的key,
Object 類型的值存儲參數。

mapper 文件使用 # { key } 引用參數值。

接口方法:

List<Student> selectMultiMap(Map<String,Object> map);

mapper 文件:

<select id="selectMultiMap" resultType="com.md.domain.Student">

select id,name,email,age from student where name=#{myname} or age =#{myage}

</select>

測試方法:

@Test

public void testSelectMultiMap(){

Map<String,Object> data = new HashMap<>();

data.put("myname"," 李白");// #{myname}

data.put("myage",20); // #{myage}

List<Student> stuList = studentDao.selectMultiMap(data);

stuList.forEach( stu -> System.out.println(stu));

}

6. # 和 $(重點)

# :占位符,告訴 mybatis 使用實際的參數值代替。並使用 PrepareStatement 對象執行 sql 語句, #{…}代替sql 語句的“?”。這樣做更安全,更迅速,通常也是首選做法

mapper 文件

<select id="selectById" resultType="com.md.domain.Student">

select id,name,email,age from student where id=#{studentId}

</select>

轉為 MyBatis 的執行是:

String sql=” select id,name,email,age from student where id=?”;

PreparedStatement ps = conn.prepareStatement(sql);

ps.setInt(1,1005);

解釋:

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

ps.setInt(1,1005) , 1005 會替換掉 #{studentId}

$ 字符串替換, ,告訴 mybatis 使用$包含的“字符串”替換所在位置。使用 Statement 把 sql 語句和${}的內容連接起來

主要用在替換表名,列名,不同列排序等操作
分別使用 id , email 列查詢 Student
接口方法:

Student findById(int id);
Student findByEmail(String email);

mapper 文件:

<select id="findById" resultType="com.md.domain.Student">

select * from student where id=#{studentId}

</select>

<select id="findByEmail" resultType="com.md.domain.Student">
select * from student where email=#{stuentEmail}
</select>

測試方法:

@Test

public void testFindStuent(){

Student student1 = studentDao.findById(1002);

System.out.println("findById:"+student1);

Student student2 = studentDao.findByEmail("zhou@126.net");

System.out.println("findByEmail:"+student2);

}

通用方法,使用不同列作為查詢條件

接口方法:

Student findByDiffField(@Param("col") String colunName,@Param("cval") Object value);

mapper 文件:

<select id="findByDiffField" resultType="com.md.domain.Student">
select * from student where ${col} = #{cval}
</select>

測試方法:

@Test

public void testFindDiffField(){

Student student1 = studentDao.findByDiffField("id",1002);

System.out.println("按 按 id 列查詢:"+student1);

Student student2 = studentDao.findByDiffField("email","zhou@126.net");

System.out.println("按 按 email 列查詢:"+student2);

}

這種方式使用更加靈活

四、總結

1. 參數

從java代碼中把實際的值傳入到mapper文件中

  1. 一個簡單 類型的參數:#{任意字符}
  2. 多個簡單類型的參數:使用@Param("自定義名稱")
  3. 使用一個java對象,對象的屬性作為mapper文件要找的參數,#{java對象的屬性名稱}
  4. 使用參數的位置,#{arg0}、#{arg1}
  5. 使用Map作為參數,#{map的key}

2. # 和 $ 的區別

  1. #是占位符,表示列的值,在等號右側
  2. $是占位符,表示字符串的連接,把sql語句連接成一個字符串
  3. #占位符使用的是jdbc指定的PrepareStatement對象執行的Sql語句,效率高,沒有sql注入的風險
  4. $占位符使用的是Statement對象執行的sql,效率低,有sql注入的風險


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM