一小時(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. 打開(kāi)連接 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開(kāi)始的 不是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. 打開(kāi)連接 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寫(xiě)別名
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 通??梢酝茢囝愋汀H欢?,如果你映射到的是 HashMap,那么你應(yīng)該明確地指定 javaType 來(lái)保證行為與期望的相一致。 |
jdbcType |
這就是數(shù)據(jù)庫(kù)對(duì)應(yīng)的類型,非必須的 |
typeHandler |
結(jié)果處理器,就是把結(jié)果再處理一次返回 后邊幾篇寫(xiě)一下自定義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ù)告:
寫(xiě)一個(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)文章
IDEA中配置多個(gè)版本的JDK的實(shí)現(xiàn)示例
IDEA可以配置多個(gè)JDK,根據(jù)需要使用不同版本的,本文就來(lái)介紹一下IDEA中配置多個(gè)版本的JDK的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-03-03
maven如何動(dòng)態(tài)統(tǒng)一修改版本號(hào)的方法步驟
這篇文章主要介紹了maven如何動(dòng)態(tài)統(tǒng)一修改版本號(hào)的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
java中重寫(xiě)equals和重寫(xiě)hashCode()
這篇文章主要介紹了java中重寫(xiě)equals和重寫(xiě)hashCode()的相關(guān)資料,需要的朋友可以參考下2017-04-04
java實(shí)現(xiàn)微信公眾平臺(tái)發(fā)送模板消息的示例代碼
這篇文章主要介紹了java實(shí)現(xiàn)微信公眾平臺(tái)發(fā)送模板消息的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
遞歸出現(xiàn)棧溢出stackoverflow的問(wèn)題及解決
這篇文章主要介紹了關(guān)于遞歸出現(xiàn)棧溢出stackoverflow的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
SpringMVC實(shí)戰(zhàn)案例RESTFul實(shí)現(xiàn)添加功能
這篇文章主要為大家介紹了SpringMVC實(shí)戰(zhàn)案例RESTFul實(shí)現(xiàn)添加功能詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Java實(shí)現(xiàn)的簡(jiǎn)單數(shù)字時(shí)鐘功能示例
這篇文章主要介紹了Java實(shí)現(xiàn)的簡(jiǎn)單數(shù)字時(shí)鐘功能,涉及java日期時(shí)間及JFrame框架圖形界面操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-02-02
SpringBoot整合Quartz實(shí)現(xiàn)動(dòng)態(tài)配置的代碼示例
這篇文章將介紹如何把Quartz定時(shí)任務(wù)做成接口,實(shí)現(xiàn)以下功能的動(dòng)態(tài)配置添加任務(wù),修改任務(wù),暫停任務(wù),恢復(fù)任務(wù),刪除任務(wù),任務(wù)列表,任務(wù)詳情,文章通過(guò)代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2023-07-07

