MyBatis(三)配置文件,輸入輸出映射,動態(tài)SQL

1.在SqlMapConfig.xml文件中加載db.properties

如果不寫db.properties的話,那么也可以直接給value賦值,但是,這樣寫的話,后果就是維護(hù)起來變得麻煩,如果下次改了密碼等信息,還需要在xml中尋找對應(yīng)的value,代碼一多的話,會很容易出錯且效率不高。相反,可以直接尋找相應(yīng)的properties文件。

db.properties代碼:

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/student
db.username=root
db.password=root

"="號左邊是鍵,盡量使用XX.XX.XX的形式,這樣更清晰。

還有一個注意的地方:

<font color=#ff0000 size=4>加載的順序</font>

<font color=#ff0000 size=4>1、 先加載properties中property標(biāo)簽聲明的屬性

2、 再加載properties標(biāo)簽引入的java配置文件中的屬性

3、 parameterType的值會和properties的屬性值發(fā)生沖突。</font>

<properties resource="db.properties">
      <property name="driver" value="com.mysql.jdbc.Driver"/>
</properties>

2.SqlMapConfig中Mapper的加載

  • 第一種方式:使用相對于類路徑的資源,通過resource標(biāo)簽直接拿到對應(yīng)的mapper

    <mapper resource="mapper/student.xml" />

  • 第二種方式:注冊指定包下的所有映射文件。通過加載Mapper接口去加載配置文件必須在同目錄下且文件名相同

    <package name="com.yu.mybatis" />

3.全局配置文件

<font color=#ff0000 size=4>SqlMapConfig.xml的配置內(nèi)容和順序如下(順序不能亂)</font>:

Properties(屬性)

Settings(全局參數(shù)設(shè)置)

typeAliases(類型別名)

typeHandlers(類型處理器)

objectFactory(對象工廠)

plugins(插件)

environments(環(huán)境信息集合)

environment(單個環(huán)境信息)

mappers(映射器)


以typeAliases(類型別名)舉例

<typeAliases>
  <typeAlias type="com.yu.domain.Student" alias="s"/>
</typeAliases>

4.輸入映射(parameterType)

1.簡單pojo
<!--更新數(shù)據(jù) -->
<update id="updateStudent" parameterType="com.yu.domain.Student">
    update student set
    name=#{name} ,age=#{age} ,hobby=#{hobby} where
    id=#{id}
</update>
2.包裝pojo類型

1)創(chuàng)建包裝類

public class StudentWrapper {
 public Student getStudent() {
    return student;
}

public void setStudent(Student student) {
    this.student = student;
}

private Student student;
 
}

2)映射文件

<!-- 包裝類型 -->
<select id="getStudentListByWrapper" parameterType="com.yu.domain.StudentWrapper"
    resultType="com.yu.domain.Student">
    select name from student where name=#{student.name}
</select>

3)Mapper接口

public interface StudentMapper {
public List<Student> getStudentListByWrapper(StudentWrapper studentWrapper)throws Exception;
}

4)測試

@Test
public void testSelectStudentListByWrapper() throws Exception {
    SqlSession session = sqlSessionFactory.openSession();
    // 拿到代理對象
    StudentMapper mapper = session.getMapper(StudentMapper.class);
    StudentWrapper studentWrapper = new StudentWrapper();
    Student students = new Student();
    students.setName("Ronaldo");

    studentWrapper.setStudent(students);
    List<Student> studentListByWrapper = mapper.getStudentListByWrapper(studentWrapper);
    System.out.println(studentListByWrapper);
    session.close();
}

5.輸出映射(resultType,resultMap)

  • resultType

<font color=#ff0000 size=4>使用resultType進(jìn)行結(jié)果映射時,需要查詢出的列名和映射的對象的屬性名一致,才能映射成功。

如果查詢的列名和對象的屬性名全部不一致,那么映射的對象為空。
如果查詢的列名和對象的屬性名有一個一致,那么映射的對象不為空,但是只有映射正確那一個屬性才有值。

如果查詢的sql的列名有別名,那么這個別名就是和屬性映射的列名。</font>:**

這里就不貼代碼了。自行測試,debug一下。。。

  • resultMap

使用resultMap進(jìn)行結(jié)果映射時,不需要查詢的列名和映射的屬性名必須一致。但是需要聲明一個resultMap,來對列名和屬性名進(jìn)行映射。

映射文件:

<!-- ResultMap的使用 -->
<select id="getStudentListByResultMap" parameterType="com.yu.domain.StudentWrapper"
    resultMap="myResultMapId">
    select name name_ from student where name=#{student.name}
</select>

resultMap的值引用上面定義resultMap的id屬性

6.動態(tài)SQL

在mybatis中,它提供了一些動態(tài)sql標(biāo)簽,可以讓程序員更快的進(jìn)行mybatis的開發(fā),這些動態(tài)sql可以通過sql的可重用性。

常用的動態(tài)sql標(biāo)簽:if標(biāo)簽、where標(biāo)簽、sql片段、foreach標(biāo)簽

If標(biāo)簽/where標(biāo)簽

<select id="getStudentByDnynaicSql" parameterType="com.yu.domain.StudentWrapper"
    resultType="com.yu.domain.Student">

    select * from student
    //where默認(rèn)去掉第一個AND
    <where>
        <if test="student!=null">
        <if test="student.name!=null and student.name!=''">
            name=#{student.name}
        </if>

        <if test="student.age!=null and student.age!=''">
            and age=#{student.age}
        </if>
    </if>
    </where>
</select>

Mapper接口:

public List<Student> getStudentByDnynaicSql(StudentWrapper studentWrapper) throws Exception;

測試代碼:

    public void getStudentByDnynaicSql() throws Exception {
    SqlSession session = sqlSessionFactory.openSession();
    // 拿到代理對象
    StudentMapper mapper = session.getMapper(StudentMapper.class);
    StudentWrapper studentWrapper = new StudentWrapper();
    Student students = new Student();
    //students.setName("Ronaldo");
    students.setAge(20);
    studentWrapper.setStudent(students);
    List<Student> studentListByWrapper = mapper.getStudentByDnynaicSql(studentWrapper);
    System.out.println(studentListByWrapper);
    session.close();
}

此時我將students.setName("Ronaldo");注釋掉。

少了name=?原因是if語句中做了判斷。

SQL片段

Sql片段可以讓代碼有更高的可重用性

Sql片段需要先定義后使用


<sql id="sqlSection">
<if test="student!=null">
<if test="student.name!=null and student.name!=''">
name=#{student.name}
</if>

        <if test="student.age!=null and student.age!=''">
            and age=#{student.age}
        </if>
    </if>
</sql>

 <select id="getStudentByDnynaicSql" parameterType="com.yu.domain.StudentWrapper"
    resultType="com.yu.domain.Student">

    select * from student
    <where>
        <include refid="sqlSection"></include>
    </where>
</select>

使用sql標(biāo)簽定義sql片段,用include標(biāo)簽引入sql片段

foreach

1) 修改包裝pojo

public class StudentWrapper {
 public Student getStudent() {
    return student;
}

public void setStudent(Student student) {
    this.student = student;
}

private Student student;
private List<Integer> list;
public List<Integer> getList() {
    return list;
}

public void setList(List<Integer> list) {
    this.list = list;
}
 
}

2)映射文件:

<!-- foreach標(biāo)簽 -->
<select id="selectStudentByforeach" resultType="com.yu.domain.Student" 
    parameterType="com.yu.domain.StudentWrapper"> 
     select * from student 
     <where>
     <foreach collection="list" item="items" open="And 
    (" close=")" separator="or">
    age=#{items} 
    </foreach>
     </where>
 </select>

Mapper接口:

public List<Student> selectStudentByforeach(StudentWrapper studentWrapper) throws Exception;

測試:

@Test
public void getStudentByDnynaicSql() throws Exception {
    SqlSession session = sqlSessionFactory.openSession();
    // 拿到代理對象
    StudentMapper mapper = session.getMapper(StudentMapper.class);
    StudentWrapper studentWrapper = new StudentWrapper();
    List<Integer> list=new ArrayList<>();
    list.add(10);
    list.add(20);
    studentWrapper.setList(list);
     List<Student> selectStudentByforeach = mapper.selectStudentByforeach(studentWrapper);
    System.out.println(selectStudentByforeach);
    session.close();
}

6.mybatis與hibernate的區(qū)別及各自應(yīng)用場景

Mybatis技術(shù)特點(diǎn):

1、 通過直接編寫SQL語句,可以直接對SQL進(jìn)行性能的優(yōu)化;

2、 學(xué)習(xí)門檻低,學(xué)習(xí)成本低。只要有SQL基礎(chǔ),就可以學(xué)習(xí)mybatis,而且很容易上手;

3、 由于直接編寫SQL語句,所以靈活多變,代碼維護(hù)性更好。

4、 不能支持?jǐn)?shù)據(jù)庫無關(guān)性,即數(shù)據(jù)庫發(fā)生變更,要寫多套代碼進(jìn)行支持,移植性不好。

Hibernate技術(shù)特點(diǎn):

1、 標(biāo)準(zhǔn)的orm框架,程序員不需要編寫SQL語句。

2、 具有良好的數(shù)據(jù)庫無關(guān)性,即數(shù)據(jù)庫發(fā)生變化的話,代碼無需再次編寫。

3、 學(xué)習(xí)門檻高,需要對數(shù)據(jù)關(guān)系模型有良好的基礎(chǔ),而且在設(shè)置OR映射的時候,需要考慮好性能和對象模型的權(quán)衡。

4、 程序員不能自主的去進(jìn)行SQL性能優(yōu)化。

Mybatis應(yīng)用場景:

需求多變的互聯(lián)網(wǎng)項(xiàng)目,例如電商項(xiàng)目。

Hibernate應(yīng)用場景:

需求明確、業(yè)務(wù)固定的項(xiàng)目,例如OA項(xiàng)目、ERP項(xiàng)目等。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,578評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,701評論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 178,691評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,974評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,694評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,026評論 1 329
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,015評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,193評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,719評論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,442評論 3 360
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,668評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,151評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,846評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,255評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,592評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,394評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,635評論 2 380

推薦閱讀更多精彩內(nèi)容