溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Mybatis中Prepared Statement與符號怎么用

發(fā)布時間:2021-09-14 17:51:08 來源:億速云 閱讀:153 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹Mybatis中Prepared Statement與符號怎么用,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

一、用一用 PreparedStatement

import java.math.BigDecimal;
import java.sql.*;

/**
 * @author 發(fā)現(xiàn)更多精彩  關(guān)注公眾號:木子的晝夜編程
 * 一個生活在互聯(lián)網(wǎng)底層,做著增刪改查的碼農(nóng),不諳世事的造作
 * @create 2021-08-25 21:26
 */
public class TestMain {
    public static void main(String[] args) throws Exception {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet result = null;
        try {
            // 1. 注冊驅(qū)動
            Class.forName("com.mysql.jdbc.Driver");
            // 2. 打開連接 url 、 用戶名、 密碼
            conn = DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/test?useSSL=false",
                    "root",
                    "123456");
            // 3. 創(chuàng)建Statenebt
            stmt = conn.prepareStatement("select * from test where name = ?");
            // 4. 設(shè)置參數(shù) 注意啦,參數(shù)下標是從1開始的 不是0哦
            stmt.setString(1, "小強");
            // 5. 執(zhí)行查詢
            result = stmt.executeQuery();
            // 6. 輸出數(shù)據(jù)庫獲取的結(jié)果
            while (result.next()){
                // 根據(jù)列名稱獲取值
                String name = result.getString("name");
                BigDecimal salary = result.getBigDecimal("salary");
                System.out.println(name+" 的工資是:"+salary);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 關(guān)閉資源
            // 關(guān)閉資源
            try{
                if(result!=null) {
                    result.close();
                }
            }catch(SQLException se2){
                System.err.println("關(guān)閉result異常");
            }
            try{
                if(stmt!=null) {
                    stmt.close();
                }
            }catch(SQLException se2){
                System.err.println("關(guān)閉stmt異常");
            }
            try{
                if(conn!=null) {
                    conn.close();
                }
            }catch(SQLException se){
                System.err.println("關(guān)閉conn異常");
            }
        }

    }
}

二、用一用 Statement

import java.math.BigDecimal;
import java.sql.*;

/**
 * @author 發(fā)現(xiàn)更多精彩  關(guān)注公眾號:木子的晝夜編程
 * 一個生活在互聯(lián)網(wǎng)底層,做著增刪改查的碼農(nóng),不諳世事的造作
 */
public class TestMain02 {
    public static void main(String[] args) throws Exception {
        Connection conn = null;
        Statement stmt = null;
        ResultSet result = null;
        try {
            // 1. 注冊驅(qū)動
            Class.forName("com.mysql.jdbc.Driver");
            // 2. 打開連接 url 、 用戶名、 密碼
            conn = DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/test?useSSL=false",
                    "root",
                    "123456");
            // 3. 創(chuàng)建Statenebt
            stmt = conn.createStatement();
            // 4. 執(zhí)行查詢
            result = stmt.executeQuery("select * from test where name = '小強'");
            // 5. 輸出數(shù)據(jù)庫獲取的結(jié)果
            while (result.next()){
                // 根據(jù)列名稱獲取值
                String name = result.getString("name");
                BigDecimal salary = result.getBigDecimal("salary");
                System.out.println(name+" 的工資是:"+salary);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 關(guān)閉資源
            // 關(guān)閉資源
            try{
                if(result!=null) {
                    result.close();
                }
            }catch(SQLException se2){
                System.err.println("關(guān)閉result異常");
            }
            try{
                if(stmt!=null) {
                    stmt.close();
                }
            }catch(SQLException se2){
                System.err.println("關(guān)閉stmt異常");
            }
            try{
                if(conn!=null) {
                    conn.close();
                }
            }catch(SQLException se){
                System.err.println("關(guān)閉conn異常");
            }
        }

    }
}

三、Mybatis #{} ${} 的使用

#{}使用

// #{}  根據(jù)名稱查詢數(shù)據(jù)
List<TestEntity> listByName01(String name);
<!--#{} 查詢數(shù)據(jù)-->
<select id="listByName01" resultType="testentity">
    select * from test where name = #{name}
</select>
import dao.TestMapper;
import entity.TestEntity;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.List;

/**
 * @author 發(fā)現(xiàn)更多精彩  關(guān)注公眾號:木子的晝夜編程
 * 一個生活在互聯(lián)網(wǎng)底層,做著增刪改查的碼農(nóng),不諳世事的造作
 */
public class TestMain03 {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            // 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
            TestMapper mapper = session.getMapper(TestMapper.class);
            // 1.#{}
            List<TestEntity> res = mapper.listByName01("小強");
            // 這個執(zhí)行的sql : select * from test where name = '小強 '
            System.out.println("第一次查詢條數(shù):"+res.size());
            List<TestEntity> res02 = mapper.listByName01("小強  or 1=1");
            // 這個執(zhí)行的sql: select * from test where name = '小強  or 1=1'
            System.out.println("第二次查詢條數(shù):"+res02.size());
        }
    }
}

${}使用

// ${}  根據(jù)名稱查詢數(shù)據(jù)
List<TestEntity> listByName02(@Param("name") String name);
<!--${} 查詢數(shù)據(jù)-->
<select id="listByName02" resultType="testentity">
    select * from test where name = ${name}
</select>
import dao.TestMapper;
import entity.TestEntity;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

/**
 * @author 發(fā)現(xiàn)更多精彩  關(guān)注公眾號:木子的晝夜編程
 * 一個生活在互聯(lián)網(wǎng)底層,做著增刪改查的碼農(nóng),不諳世事的造作
 */
public class TestMain04 {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            // 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
            TestMapper mapper = session.getMapper(TestMapper.class);
            // 1.${} 這里還得自己加個單引號 要不然sql就不對了
            List<TestEntity> res = mapper.listByName02("'小強'");
            // 執(zhí)行的sql: select * from test where name = '小強'
            System.out.println("第一次:"+res.size());
            List<TestEntity> res02 = mapper.listByName02("'小強 ' or 1=1 ");
            // 執(zhí)行的sql(可怕哦): select * from test where name = '小強 ' or 1=1
            System.out.println("第二次:"+res02.size());
        }
    }
}

#{} 使用的是PrepareStatment 用的是 ‘?' 占位符 不會被SQL注入 不管你輸出什么都會給你用單引號包起來

類似這種:

public class TestMain05 {
    public static void main(String[] args)   {
        String sql = "select * from test where name = '?' ";
        String name = "小強";
        sql = sql.replace("?", name);
        System.out.println(sql);
        // select * from test where name = '小強' 
    }
}

${}他就相當于是普通的拼接 你傳入什么就原封不動的給你放到Sql后邊

類似這種:

public class TestMain06 {
    public static void main(String[] args)   {
        String sql = "select * from test where name = ?";
        String name = "'小強'";
        sql = sql.replace("?", name);
        System.out.println(sql);
    }
}

四、ResultMap ResultType的區(qū)別

resultType使用方式我們已經(jīng)用過很多次了,這里先下一個resultMap的使用方式

<resultMap id="testResultMap" type="testentity">
    <id property="id" column="id" javaType="long" jdbcType="BIGINT"/>
    <result property="name" column="name" javaType="string" jdbcType="VARCHAR"/>
    <result property="age" column="name" javaType="int" jdbcType="INTEGER"/>
    <result property="salary" column="name" javaType="decimal" jdbcType="DECIMAL"/>
 </resultMap>

 <select id="testResultMap" resultMap="testResultMap">
    select * from test
 </select>

resultType、resultMap功能類似,都是返回對象信息,但是resultMap要更強大一些,可以實現(xiàn)自定義。

我們一般項目中數(shù)據(jù)庫都是下劃線比如course_date 但是實體類中都是用courseDate 所以大部分時候都需要進行名稱匹配都會用到resultMap 或者 sql寫別名

sql別名方式:

<select id="list" resultType="testentity">
    select
    id as id
    name as name
    age as age
    course_date as courseDate
    from test
</select>

id&result

他倆都是將一列值映射到一個簡單的數(shù)據(jù)類型(String、int、double、Date等)的屬性或字段。

他倆唯一的不同是:id元素對應的屬性會被標記為對象的標識符,在比較對象實例的時候使用。這樣可以提升整體的性能,尤其是進行緩存和嵌套結(jié)果映射的時候。

他倆都有一些屬性:

屬性描述
property映射到列結(jié)果的字段或?qū)傩?/td>
column數(shù)據(jù)庫中的列名,或者是列的別名。一般情況下,這和傳遞給 resultSet.getString(columnName) 方法的參數(shù)一樣。
就是數(shù)據(jù)庫列名
javaType一個 Java 類的全限定名,或一個類型別名 如果你映射到一個 JavaBean,MyBatis 通??梢酝茢囝愋汀H欢?,如果你映射到的是 HashMap,那么你應該明確地指定 javaType 來保證行為與期望的相一致。
jdbcType這就是數(shù)據(jù)庫對應的類型,非必須的
typeHandler結(jié)果處理器,就是把結(jié)果再處理一次返回 后邊幾篇寫一下自定義typeHandler

在中文官網(wǎng)上找了個例子:

<!-- 非常復雜的結(jié)果映射 -->
<resultMap id="detailedBlogResultMap" type="Blog">
  <constructor>
    <idArg column="blog_id" javaType="int"/>
    <arg  column="name" javaType="varchar"></arg>
  </constructor>
  <result property="title" column="blog_title"/>
  <association property="author" javaType="Author">
    <id property="id" column="author_id"/>
    <result property="username" column="author_username"/>
    <result property="password" column="author_password"/>
    <result property="email" column="author_email"/>
    <result property="bio" column="author_bio"/>
    <result property="favouriteSection" column="author_favourite_section"/>
  </association>
  <collection property="posts" ofType="Post">
    <id property="id" column="post_id"/>
    <result property="subject" column="post_subject"/>
    <association property="author" javaType="Author"/>
    <collection property="comments" ofType="Comment">
      <id property="id" column="comment_id"/>
    </collection>
    <collection property="tags" ofType="Tag" >
      <id property="id" column="tag_id"/>
    </collection>
    <discriminator javaType="int" column="draft">
      <case value="1" resultType="DraftPost"/>
    </discriminator>
  </collection>
</resultMap>

constructor: 用于實例化類時,注入結(jié)果到構(gòu)造方法中

idArg:這個就是主鍵ID

arg:這個就是普通字段

association: 一個復雜類型的關(guān)聯(lián) 對象里字段是對象

collection:一個復雜的類型關(guān)聯(lián) 對象里字段是集合

discriminator: 使用結(jié)果值來確認使用哪個resultMap

以上是“Mybatis中Prepared Statement與符號怎么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI