一小時(shí)迅速入門Mybatis之Prepared Statement與符號(hào)的使用
引入Mysql的Jar包以及表結(jié)構(gòu)前幾篇已經(jīng)有了這里就不贅述了
一、用一用 PreparedStatement
import java.math.BigDecimal; import java.sql.*; /** * 一個(gè)生活在互聯(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. 注冊(cè)驅(qū)動(dòng) 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ù)下標(biāo)是從1開始的 不是0哦 stmt.setString(1, "小強(qiáng)"); // 5. 執(zhí)行查詢 result = stmt.executeQuery(); // 6. 輸出數(shù)據(jù)庫(kù)獲取的結(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.*; /** * 一個(gè)生活在互聯(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. 注冊(cè)驅(qū)動(dòng) 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 = '小強(qiáng)'"); // 5. 輸出數(shù)據(jù)庫(kù)獲取的結(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; /** * 一個(gè)生活在互聯(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()) { // 通過(guò)sesson獲取Mapper 這個(gè)Mapper會(huì)編程Mybatis的代理Mapper TestMapper mapper = session.getMapper(TestMapper.class); // 1.#{} List<TestEntity> res = mapper.listByName01("小強(qiáng)"); // 這個(gè)執(zhí)行的sql : select * from test where name = '小強(qiáng) ' System.out.println("第一次查詢條數(shù):"+res.size()); List<TestEntity> res02 = mapper.listByName01("小強(qiáng) or 1=1"); // 這個(gè)執(zhí)行的sql: select * from test where name = '小強(qiáng) 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; /** * 一個(gè)生活在互聯(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()) { // 通過(guò)sesson獲取Mapper 這個(gè)Mapper會(huì)編程Mybatis的代理Mapper TestMapper mapper = session.getMapper(TestMapper.class); // 1.${} 這里還得自己加個(gè)單引號(hào) 要不然sql就不對(duì)了 List<TestEntity> res = mapper.listByName02("'小強(qiáng)'"); // 執(zhí)行的sql: select * from test where name = '小強(qiáng)' System.out.println("第一次:"+res.size()); List<TestEntity> res02 = mapper.listByName02("'小強(qiáng) ' or 1=1 "); // 執(zhí)行的sql(可怕哦): select * from test where name = '小強(qiáng) ' or 1=1 System.out.println("第二次:"+res02.size()); } } }
#{}
使用的是PrepareStatment 用的是 ‘?' 占位符 不會(huì)被SQL注入 不管你輸出什么都會(huì)給你用單引號(hào)包起來(lái)
類似這種:
public class TestMain05 { public static void main(String[] args) { String sql = "select * from test where name = '?' "; String name = "小強(qiáng)"; sql = sql.replace("?", name); System.out.println(sql); // select * from test where name = '小強(qiáng)' } }
${}
他就相當(dāng)于是普通的拼接 你傳入什么就原封不動(dòng)的給你放到Sql后邊
類似這種:
public class TestMain06 { public static void main(String[] args) { String sql = "select * from test where name = ?"; String name = "'小強(qiáng)'"; sql = sql.replace("?", name); System.out.println(sql); } }
四、ResultMap ResultType的區(qū)別
resultType使用方式我們已經(jīng)用過(guò)很多次了,這里先下一個(gè)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功能類似,都是返回對(duì)象信息,但是resultMap要更強(qiáng)大一些,可以實(shí)現(xiàn)自定義。
我們一般項(xiàng)目中數(shù)據(jù)庫(kù)都是下劃線比如course_date 但是實(shí)體類中都是用courseDate 所以大部分時(shí)候都需要進(jìn)行名稱匹配都會(huì)用到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
他倆都是將一列值映射到一個(gè)簡(jiǎn)單的數(shù)據(jù)類型(String、int、double、Date等)的屬性或字段。
他倆唯一的不同是:id元素對(duì)應(yīng)的屬性會(huì)被標(biāo)記為對(duì)象的標(biāo)識(shí)符,在比較對(duì)象實(shí)例的時(shí)候使用。這樣可以提升整體的性能,尤其是進(jìn)行緩存和嵌套結(jié)果映射的時(shí)候。
他倆都有一些屬性:
屬性 | 描述 |
---|---|
property |
映射到列結(jié)果的字段或?qū)傩?/td> |
column |
數(shù)據(jù)庫(kù)中的列名,或者是列的別名。一般情況下,這和傳遞給 resultSet.getString(columnName) 方法的參數(shù)一樣。就是數(shù)據(jù)庫(kù)列名 |
javaType |
一個(gè) Java 類的全限定名,或一個(gè)類型別名 如果你映射到一個(gè) JavaBean,MyBatis 通??梢酝茢囝愋?。然而,如果你映射到的是 HashMap,那么你應(yīng)該明確地指定 javaType 來(lái)保證行為與期望的相一致。 |
jdbcType |
這就是數(shù)據(jù)庫(kù)對(duì)應(yīng)的類型,非必須的 |
typeHandler |
結(jié)果處理器,就是把結(jié)果再處理一次返回 后邊幾篇寫一下自定義typeHandler |
在中文官網(wǎng)上找了個(gè)例子:
<!-- 非常復(fù)雜的結(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: 用于實(shí)例化類時(shí),注入結(jié)果到構(gòu)造方法中
idArg:這個(gè)就是主鍵ID
arg:這個(gè)就是普通字段
association: 一個(gè)復(fù)雜類型的關(guān)聯(lián) 對(duì)象里字段是對(duì)象
collection:一個(gè)復(fù)雜的類型關(guān)聯(lián) 對(duì)象里字段是集合
discriminator: 使用結(jié)果值來(lái)確認(rèn)使用哪個(gè)resultMap
下集預(yù)告:
寫一個(gè)復(fù)雜點(diǎn)的返回結(jié)果resultMap案例
動(dòng)態(tài)SQL 常用標(biāo)簽
到此這篇關(guān)于一小時(shí)迅速入門Mybatis之Prepared Statement與符號(hào)的使用的文章就介紹到這了,更多相關(guān)Mybatis Prepared Statement內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatis利用攔截器實(shí)現(xiàn)數(shù)據(jù)脫敏詳解
現(xiàn)代網(wǎng)絡(luò)環(huán)境中,敏感數(shù)據(jù)的處理是至關(guān)重要的,敏感數(shù)據(jù)包括個(gè)人身份信息、銀行賬號(hào)、手機(jī)號(hào)碼等,所以本文主要為大家詳細(xì)介紹了MyBatis如何利用攔截器實(shí)現(xiàn)數(shù)據(jù)脫敏,希望對(duì)大家有所幫助2023-11-11java servlet手機(jī)app訪問(wèn)接口(一)數(shù)據(jù)加密傳輸驗(yàn)證
這篇文章主要為大家詳細(xì)介紹了java servlet手機(jī)app訪問(wèn)接口(一),數(shù)據(jù)加密傳輸驗(yàn)證,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12基于springMvc+hibernate的web application的構(gòu)建
下面小編就為大家?guī)?lái)一篇基于springMvc+hibernate的web application的構(gòu)建。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-10-10SpringBoot中EasyExcel實(shí)現(xiàn)Excel文件的導(dǎo)入導(dǎo)出
這篇文章主要介紹了SpringBoot中EasyExcel實(shí)現(xiàn)Excel文件的導(dǎo)入導(dǎo)出,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10Java?C++題解leetcode769最多能完成排序的塊
這篇文章主要為大家介紹了Java?C++題解leetcode769最多能完成排序的塊示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10java 中模擬UDP傳輸?shù)陌l(fā)送端和接收端實(shí)例詳解
這篇文章主要介紹了java 中模擬UDP傳輸?shù)陌l(fā)送端和接收端實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03完美解決idea moudle沒(méi)有藍(lán)色的小方塊的問(wèn)題
這篇文章主要介紹了完美解決idea moudle沒(méi)有藍(lán)色的小方塊的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02