1. 程式人生 > >mybatis動態sql以及reslutType和resultMap詳解

mybatis動態sql以及reslutType和resultMap詳解

全域性配置檔案,以及sql.properties

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <!--   載入jdbcproperties
 要解除安裝configuration和environment之間 
  -->
    <properties
resource="com/leige/config/jdbcInfo.properties">
</properties> <!-- 別名宣告,告訴mybatis,Student對應的類型別 使其能將Student這個字元和Student類對應起來 類型別名是為 Java 型別設定一個短的名字。它只和 XML 配置有關,存在的意義僅在於用來減少類完全限定名的冗餘 即在任何需要使用com.leige.domain.Student的地方都可以使用Student --> <typeAliases> <!-- 宣告po類別名 -->
<typeAlias alias="Student" type="com.leige.domain.Student"/> <!-- 宣告組合查詢類 --> <typeAlias alias="StudentQueryVo" type="com.leige.domain.StudentQueryVo" /> </typeAliases> <!-- 環境配置,資料庫連線引數 --> <environments default="development"> <environment
id="development">
<transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!-- 將操作sql集合加入配置檔案 --> <mappers> <mapper resource="com/leige/domain/Student.xml"/> </mappers> </configuration>

jdbc配置

driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\:///test
username=root
password=

首先介紹resultType和resultMap區別:

簡單介紹下resultType和resultMap的區別: resultType可以理解為實現po類屬性到資料庫表的對映,不支援別名查詢
即使用 select sid sid_,age age_,name sname from student where
sid=1時,如果使用resultType接收結果, 會發生資料丟失即sid,age,name無法注入到物件中
這時候可以使用resultMap 1:使用resultMap之前要先定義resultMap column:資料列名
property:po類屬性名 例如:

<resultMap type="Student" id="studentMap">
<!--     type表示轉換的型別,id唯一表示resultMap,
如果在別的對映檔案中使用此resultMap,需要加上名稱空間,即Student.studentMap -->
<id column="sid_" property="sid" />
<result column="age_" property="age"/>
<result column="name_" property="name" />
</resultMap>

動態sql在實際應用程式碼中解釋*
**當我們需要傳入多個sid,查詢多個物件或者物件屬性組合查詢?如何使mybatis滿足要求
這就需要使用條件了這時我們可以定義一個物件,包含所有的查詢條件StudentQueryVo,使用sql片段來實現,動態的拼接sql語句
注意:
1:定義sql片段時儘量使用單表sql,這樣可重用性才高
2:sql片段不要包含where****

實體類:

``
public class Student {
private Integer sid;
private String name;
private Integer age;
setter..
getter...
toString....
}

*StudentQueryVo查詢類:*

public class StudentQueryVo {
    //集合型別的值例項化,可以根據使用習慣在內部還是外部
    //傳入多個sid查詢多個物件
    private List<Integer> sids=new ArrayList<Integer>();
    //傳入多個name查詢多個物件
    private List<String> names=new ArrayList<String>();
    //傳入多個age查詢多個物件
    private List<Integer> ages=new ArrayList<Integer>();
    //物件屬性組合查詢
    private Student student;
            setter..
            getter...
            toString....
    }

SqlUtils工具類:

package com.leige.test;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


/**
 * @author sqlsession工具類
 *
 */
public class SqlUtils {
    static SqlSessionFactory factory;
    //靜態載入session工廠
    static{
        InputStream inputStream;
        try {
            inputStream = Resources.getResourceAsStream("com/leige/config/configuration.xml");
            //1:例項化sqlsessionfactory工廠
            factory= new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {

        }


    }
    public static SqlSession getSession() {
        try{

        //開啟session
        return factory.openSession();
        }catch(Exception e){

            throw new RuntimeException(e);
        }
    }
    /**
     * @param session
     * @param mapper
     * @return
     * 保證會話session一致,所以當做引數傳過來
     */
    public static Object getmaMapper(SqlSession session,Class mapper){

        //註冊對映介面
        factory.getConfiguration().addMapper(mapper);
        //返回操作例項
        return session.getMapper(mapper);
    }

}

測試類:

package com.leige.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.leige.domain.Student;
import com.leige.domain.StudentQueryVo;

public class App {
    /**
     * 測試使用resultMap
     */
    @Test
    public void testSelect(){

            SqlSession session=SqlUtils.getSession();

            //map查詢
            Student student=session.selectOne("Student.selectResultMap", 1);
            //Student student=session.selectOne("Student.selectStudent", 1);
            System.out.println(student);
            session.close();

    }
    /**
     * 測試sql片段
     */
    @Test
    public void testSelectSql(){
        //獲取session
            SqlSession session=SqlUtils.getSession();
            //例項多條件組合查詢bean類
            StudentQueryVo queryVo=new StudentQueryVo();
            //設定多值查詢,其他屬性操作類似
            queryVo.getSids().add(1);
            queryVo.getSids().add(2);
            queryVo.getSids().add(3);
            //查詢
            List<Student> students=session.selectList("Student.selectMultiply",queryVo);
            //輸出
            for(Student stu:students)
                System.out.println(stu);
}


    /**
     * 測試sql變短多屬性組合查詢
     */
    @Test
    public void testSelectSql2(){
        //獲取session
        SqlSession session=SqlUtils.getSession();
        //例項多條件組合查詢bean類
        StudentQueryVo queryVo=new StudentQueryVo();
        //設定多屬性組合查詢
        Student student=new Student();
        student.setAge(22);
        student.setName("leige");
        queryVo.setStudent(student);
        queryVo.getSids().add(1);
        queryVo.getSids().add(2);
        //組合查詢
        List<Student> students=session.selectList("Student.selectMultiply",queryVo);
        //輸出
        for(Student stu:students)
            System.out.println(stu);

    }
}

相關推薦

mybatis動態sql以及reslutTyperesultMap

全域性配置檔案,以及sql.properties <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration

Mybatis中@Param的用法作用

用註解來簡化xml配置的時候,@Param註解的作用是給引數命名,引數命名後就能根據名字得到引數值,正確的將引數傳入sql語句中我們先來看Mapper介面中的@Select方法?1234567package Mapper; public interface Mapper {

MyBatis動態sql之${}#{}區別

where 語句 替換字符串 客戶端 字符 註釋 tab reason mybatis 前言 ? 接觸mybatis也是在今年步入社會之後,想想也半年多了,缺沒時間去系統的學習,只知道大概,也是慚愧。 ? 不知道有多少剛畢業的同學和我一樣,到現在還沒仔仔細細去了解你每天都會

mybatis 動態sql 的筆記 以及標簽

hang clas prope AS 正常 標簽 not in IE zhang MyBatis常用OGNL表達式 e1 or e2 e1 and e2 e1 == e2,e1 eq e2 e1 != e2,e1 neq e2 e1 lt e2:小於 e1 lte e2:

程式筆記:MyBatis 動態SQL模糊查詢

之前用mybatis在xml中寫sql語句用到過<if>標籤,但是不知道這是動態SQL(尷尬),最近空閒整理一下常用的動態SQL。好記性不如爛筆頭 以圖 t_user 表為例: 1. if 語句 根據 userNo 和 name 來查詢資料。如果userNo為空

Mybatis 動態SQL

id :在名稱空間中唯一的識別符號,可以用來引用這條語句parameterType:將會傳入這條SQL語句的引數類的完全限定名或別名parameterMap:這是引用外部parameterMap的已經廢棄的方法,使用內聯引數對映和ParameterType屬性。resultType:從這條語句返回的期望型別的

Mybatis 動態SQL關聯對映

MyBatis動態SQL 可以在MyBatis動態拼湊SQL語句,MyBatis提供了一套標籤,可以實現在XML中動態構建一個SQL語句。與JSTL相似 標籤: … .. .. ..

MyBatis學習筆記-08.MyBatis動態Sql語句foreach的collection的用法以及用foreach實現批量刪除與批量新增

本次將繼續記MyBatis動態Sql語句的choose和foreach:一、choose(較少應用):有時我們不想應用到所有的條件語句,而只想從中擇其一項。針對這種情況,MyBatis 提供了 choo

Mybatis---動態SQL(四)

(一)動態SQL簡介     使用JDBC對資料庫進行操作,通常需要根據需求手動的拼接SQL或重新編寫SQL語句,這是一項非常無聊和麻煩的操作,但是Mybatis提供了對SQL語句動態組裝的功能,恰好解決這一項麻煩的操作。 參考: Mybatis官方文件

超全MyBatis動態SQL

標簽 2.3 去除 mean not null 3.2 false foreach rtl MyBatis 令人喜歡的一大特性就是動態 SQL。在使用 JDBC 的過程中, 根據條件進行 SQL 的拼接是很麻煩且很容易出錯的。MyBatis 動態 SQL 的出現, 解決了這

MyBatis動態SQL————MyBatis動態SQL標簽的用法

efi 數組 cnblogs 朋友 正常 scm jdbc pojo 動態語言 1.MyBatis動態SQL MyBatis 的強大特性之一便是它的動態 SQL,即拼接SQL字符串。如果你有使用 JDBC 或其他類似框架的經驗,你就能體會到根據不同條件拼接 SQL 語句有多

4.mybatis動態SQL拼接/取值/OGNL

align log 值方法 enter png 動態 mybatis框架 -a ognl 4.mybatis動態SQL拼接/取值 一、mybatis框架的SQL拼接是采用OGNL表達式進行的,以下我會列出常用的取值方法。 圖片來源:慕課網 1.1常用的取值方法: 1.2特

MyBatis-動態SQL

convert 指定 app 數組 bject end sep name over 動態SQL是MyBatis的一個強大的特性。MyBatis 使用了基於強大的 OGNL(Object-Graph Navigation Language 的縮寫,它是一種功能強大的表達式語言

MyBatis基礎:MyBatis動態SQL(3)

span column foreach param ati when nbsp base condition 1. 概述   MyBatis中動態SQL包括元素: 元素作用備註 if 判斷語句 單條件分支判斷 choose(when、othe

MyBatis動態SQL

lis array bat cti mybatis 映射 foreach 替代 進行  MyBatis在SQL映射文件中可以使用靈活,智能的動態SQL來實現SQL映射。   if+set:完成更新操作   if+where:完成多條查詢   if+trim:完成多條件查詢(

MyBatis 動態SQL

互斥 pda 1.3 null del 復制代碼 條件 rri mybatis MyBatis動態SQL:   動態SQL是在運行時生成和執行SQL的編程方法    動態是和靜態相對而言的。靜態SQL指的是在代碼編譯時刻就已經包含在代碼中的那些已經充分明確的固定的SQ

mybatis動態sql排序無效

ati 例如 str 但是 sql ron 們的 問題 生成 order by 字段,在用動態sql時會出現問題,排序無效,而且在日誌裏查詢不到,不能發現這個錯誤。 通常,咱們的動態sql一般都會用#代替$,因為#可以防止sql註入問題。 但是在order by的字段裏,如

mybatis 動態sql 插入報錯

method div exce 必須 字段 timeval blog ora eval 1. 值為null必須制定jdbcType 單條執行的話,可以考慮把值為null的字段去掉 2. 值的類型無法解析 比如oracle.sql.TIMESTAMP類型,需轉

Linux route命令使用,以及網卡命令

linux 路由 網卡一 路由的基礎知識:1)路由概念路由: 跨越從源主機到目標主機的一個互聯網絡來轉發數據包的過程路由器:能夠將數據包轉發到正確的目的地,並在轉發過程中選擇最佳路徑的設備路由表:在路由器中維護的路由條目,路由器根據路由表做路徑選擇直連路由:當在路由器上配置了接口的IP地址,並且接口狀態為

mybatis動態SQL操作之插入學習筆記

動態SQL操作之插入學習筆記1 import java.util.ArrayList; import java.util.List; import org.apache.ibatis.session.SqlSession; import cn.itcast.javaee.mybatis.util.Myb