一小時迅速入門Mybatis之Prepared Statement與符號的使用
引入Mysql的Jar包以及表結構前幾篇已經(jīng)有了這里就不贅述了
一、用一用 PreparedStatement
import java.math.BigDecimal;
import java.sql.*;
/**
* 一個生活在互聯(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. 注冊驅動
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ù)下標是從1開始的 不是0哦
stmt.setString(1, "小強");
// 5. 執(zhí)行查詢
result = stmt.executeQuery();
// 6. 輸出數(shù)據(jù)庫獲取的結果
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 {
// 關閉資源
// 關閉資源
try{
if(result!=null) {
result.close();
}
}catch(SQLException se2){
System.err.println("關閉result異常");
}
try{
if(stmt!=null) {
stmt.close();
}
}catch(SQLException se2){
System.err.println("關閉stmt異常");
}
try{
if(conn!=null) {
conn.close();
}
}catch(SQLException se){
System.err.println("關閉conn異常");
}
}
}
}
二、用一用 Statement
import java.math.BigDecimal;
import java.sql.*;
/**
* 一個生活在互聯(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. 注冊驅動
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ù)庫獲取的結果
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 {
// 關閉資源
// 關閉資源
try{
if(result!=null) {
result.close();
}
}catch(SQLException se2){
System.err.println("關閉result異常");
}
try{
if(stmt!=null) {
stmt.close();
}
}catch(SQLException se2){
System.err.println("關閉stmt異常");
}
try{
if(conn!=null) {
conn.close();
}
}catch(SQLException se){
System.err.println("關閉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;
/**
* 一個生活在互聯(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;
/**
* 一個生活在互聯(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元素對應的屬性會被標記為對象的標識符,在比較對象實例的時候使用。這樣可以提升整體的性能,尤其是進行緩存和嵌套結果映射的時候。
他倆都有一些屬性:
| 屬性 | 描述 |
|---|---|
property |
映射到列結果的字段或屬性 |
column |
數(shù)據(jù)庫中的列名,或者是列的別名。一般情況下,這和傳遞給 resultSet.getString(columnName) 方法的參數(shù)一樣。就是數(shù)據(jù)庫列名 |
javaType |
一個 Java 類的全限定名,或一個類型別名 如果你映射到一個 JavaBean,MyBatis 通??梢酝茢囝愋?。然而,如果你映射到的是 HashMap,那么你應該明確地指定 javaType 來保證行為與期望的相一致。 |
jdbcType |
這就是數(shù)據(jù)庫對應的類型,非必須的 |
typeHandler |
結果處理器,就是把結果再處理一次返回 后邊幾篇寫一下自定義typeHandler |
在中文官網(wǎng)上找了個例子:
<!-- 非常復雜的結果映射 -->
<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: 用于實例化類時,注入結果到構造方法中
idArg:這個就是主鍵ID
arg:這個就是普通字段
association: 一個復雜類型的關聯(lián) 對象里字段是對象
collection:一個復雜的類型關聯(lián) 對象里字段是集合
discriminator: 使用結果值來確認使用哪個resultMap
下集預告:
寫一個復雜點的返回結果resultMap案例
動態(tài)SQL 常用標簽
到此這篇關于一小時迅速入門Mybatis之Prepared Statement與符號的使用的文章就介紹到這了,更多相關Mybatis Prepared Statement內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
MyBatis利用攔截器實現(xiàn)數(shù)據(jù)脫敏詳解
現(xiàn)代網(wǎng)絡環(huán)境中,敏感數(shù)據(jù)的處理是至關重要的,敏感數(shù)據(jù)包括個人身份信息、銀行賬號、手機號碼等,所以本文主要為大家詳細介紹了MyBatis如何利用攔截器實現(xiàn)數(shù)據(jù)脫敏,希望對大家有所幫助2023-11-11
java servlet手機app訪問接口(一)數(shù)據(jù)加密傳輸驗證
這篇文章主要為大家詳細介紹了java servlet手機app訪問接口(一),數(shù)據(jù)加密傳輸驗證,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12
基于springMvc+hibernate的web application的構建
下面小編就為大家?guī)硪黄趕pringMvc+hibernate的web application的構建。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
SpringBoot中EasyExcel實現(xiàn)Excel文件的導入導出
這篇文章主要介紹了SpringBoot中EasyExcel實現(xiàn)Excel文件的導入導出,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10
Java?C++題解leetcode769最多能完成排序的塊
這篇文章主要為大家介紹了Java?C++題解leetcode769最多能完成排序的塊示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10
java 中模擬UDP傳輸?shù)陌l(fā)送端和接收端實例詳解
這篇文章主要介紹了java 中模擬UDP傳輸?shù)陌l(fā)送端和接收端實例詳解的相關資料,需要的朋友可以參考下2017-03-03

