此第一次接觸Mybatis框架確實是有點不適應,特別是剛從Hibernate框架轉轉型過來,那麼為什麼要使用Mybatis框架,Mybatis框架和Hibernate框架又有什麼異同呢? 這個問題在我的另一篇blogs中有專門的講解,今天我主要是帶著大家來探討一下如何簡單的使用Mybatis這個框架 ...
此第一次接觸Mybatis框架確實是有點不適應,特別是剛從Hibernate框架轉轉型過來,那麼為什麼要使用Mybatis框架,Mybatis框架和Hibernate框架又有什麼異同呢?
這個問題在我的另一篇blogs中有專門的講解,今天我主要是帶著大家來探討一下如何簡單的使用Mybatis這個框架
可能有的朋友知道,Mybatis中是通過配置文件來實現這個的,這裡面有很多的東西,我們就一點一點的講吧
我們想要配置成功,首要的就是jar包,先從官網下載相應的jar包作為程式的支撐
有了jar包之後我麽就來看看我們程式的主要的搭建
具體類的內容如下
Student Class
package entity; /* * 學生類 * */ public class Student { //學生編號 private Integer sid; //學生名稱 private String sname; //學生性別 private String sex; public Student() { } public Student(String sname, String sex) { this.sname = sname; this.sex = sex; } public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
Grade Class
package entity; /* * 班級類 * */ public class Grade { //班級編號 private Integer gid; //班級名稱 private String gname; //班級描述 private String gdesc; public Grade() { } public Grade(Integer gid, String gname, String gdesc) { this.gid = gid; this.gname = gname; this.gdesc = gdesc; } public Integer getGid() { return gid; } public void setGid(Integer gid) { this.gid = gid; } public String getGname() { return gname; } public void setGname(String gname) { this.gname = gname; } public String getGdesc() { return gdesc; } public void setGdesc(String gdesc) { this.gdesc = gdesc; } }
接下來我麽就要配置我們的主要配置文件了,主要是指定我們要連接的資料庫和具體連接操作
Configuration.xml
<?xml version="1.0" encoding="UTF-8" ?> <!-- Copyright 2009-2012 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- <settings> <setting name="useGeneratedKeys" value="false"/> <setting name="useColumnLabel" value="true"/> </settings> <typeAliases> <typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/> </typeAliases> --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"> <property name="" value=""/> </transactionManager> <dataSource type="UNPOOLED"> <property name="driver" value="oracle.jdbc.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/> <property name="username" value="practice"/> <property name="password" value="123"/> </dataSource> </environment> </environments> <mappers> <mapper resource="config/Student.xml"/> </mappers> </configuration>
其實最主要的是如下圖所示
到這裡為止,所有的準備工作基本上就已經是完成了
接下來,使用Mybatis框架來實現我們的具體操作‘
1.查詢所有學生信息
因為Mybatis是屬於一種半自動化的框架技術所以呢sql是我們手動書寫的,這也是Mybatis的一大特點
我們可以寫出具體的實體配置文件
Student.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2009-2012 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="Student"> <resultMap type="entity.Student" id="StudentResult"> <id column="sid" jdbcType="INTEGER" property="sid"/> <result column="sname" jdbcType="VARCHAR" property="sname"/> <result column="sex" jdbcType="VARCHAR" property="sex"/> </resultMap> <select id="selectAllStu" resultMap="StudentResult"> select * from Student </select> </mapper>
既然我們寫了sql也指定了相應的實體類,那麼我們到現在為止還並沒有用到它,所以我們還需要在主配置文件中添加實體配置文件的引用
經過以上的步驟, 我們查詢全部學生的配置文件基本上就已經完成了,現在我們來進行一道測試
/* * 1.1 查詢所有的學生信息 * */ @Test public void OneTest() throws Exception{ //通過配置文件獲取到資料庫連接信息 Reader reader = Resources.getResourceAsReader("config/Configuration.xml"); //通過配置信息構建一個SessionFactory工廠 SqlSessionFactory sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader); //通過SessionFaction打開一個回話通道 SqlSession session = sqlsessionfactory.openSession(); //調用配置文件中的sql語句 List<Student> list = session.selectList("Student.selectAllStu"); //遍歷查詢出來的結果 for (Student stu : list) { System.out.println(stu.getSname()); } session.close(); }
執行之後的語句如下
這樣我們使用Mybatis查詢所有學生信息就完成了
2.帶條件查詢動態Sql拼接
/* *1.2 帶條件查詢信息(動態Sql拼接) * */ @Test public void selectAllStuByWhere() throws Exception{ //通過配置文件獲取到資料庫連接信息 Reader reader = Resources.getResourceAsReader("config/Configuration.xml"); //通過配置信息構建一個SessionFactory工廠 SqlSessionFactory sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader); //通過SessionFaction打開一個回話通道 SqlSession session = sqlsessionfactory.openSession(); //準備一個學生對象作為參數 Student student=new Student(); student.setSname("3"); //調用配置文件中的sql語句 List<Student> list = session.selectList("Student.selectAllStuByWhere",student); //遍歷查詢出來的結果 for (Student stu : list) { System.out.println(stu.getSname()); } session.close(); }
小配置配置文件信息
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2009-2012 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="Student"> <resultMap type="entity.Student" id="StudentResult"> <id column="sid" jdbcType="INTEGER" property="sid"/> <result column="sname" jdbcType="VARCHAR" property="sname"/> <result column="sex" jdbcType="VARCHAR" property="sex"/> </resultMap> <!-- 簡單查詢所有信息 --> <select id="selectAllStu" resultMap="StudentResult"> select sid,sname,sex,gid from Student </select> <!--動態拼接Sql --> <select id="selectAllStuByWhere" parameterType="entity.Student" resultMap="StudentResult"> select sid,sname,sex,gid from Student where 1=1 <if test="sname!=null and !"".equals(sname.trim())"> and sname like '%'|| #{sname}|| '%' <!-- 模糊查詢 --> <!-- and sname = #{sname} --> </if> </select> </mapper>
執行之後的結果就是
3.新增學生信息
/* * 1.3 新增學生信息 * * */ @Test public void InsertStuInfo() throws Exception{ //通過配置文件獲取配置信息 Reader reader = Resources.getResourceAsReader("config/Configuration.xml"); //構建一個SessionFactory,傳入配置文件 SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader); //獲取session SqlSession session = factory.openSession(); //準備參數對象 Student stu=new Student(); stu.setSname("巴黎的雨季"); stu.setSex("男"); //調用添加方法 int count = session.insert("Student.InsertStuInfo", stu); if(count>0){ System.out.println("添加成功"); }else{ System.out.println("添加失敗"); } //提交 session.commit(); //關閉 session.close(); }
在小配置中增加一個節點
<!-- 新增學生信息 --> <insert id="InsertStuInfo" parameterType="entity.Student" > insert into Student values(SEQ_NUM.Nextval,#{sname},#{sex},1) </insert>
執行之後結果為
後續的刪除和修改代碼基本上和新增是一致的,只是調用的sql語句不同,所以後續我就不做詳細的解釋了,只將代碼擺出來,詳細大家都能夠看得明白!!
4.刪除學生信息根據id
/* * 1.4根據SID刪除學生信息 * */ @Test public void DeleteStuBySid()throws Exception{ //通過配置文件獲取配置信息 Reader reader = Resources.getResourceAsReader("config/Configuration.xml"); //構建一個SessionFactory,傳入配置文件 SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader); //獲取session SqlSession session = factory.openSession(); //準備參數 int sid=2; //調用刪除方法 int count = session.delete("Student.DeleteStuBySid", sid); if(count>0){ System.out.println("刪除成功"); }else{ System.out.println("刪除失敗"); } //提交 session.commit(); //關閉 session.close(); }
需要在配置文件中新增的是
<!-- 刪除學生信息 --> <insert id="DeleteStuBySid" parameterType="int"> delete from Student where sid=#{sid} <!--或者是 delete from Student where sid=#{_parameter} --> </insert>
5.根據SID修改學生信息
/* * 1.5根據SID修改學生信息 * * */ @Test public void UpdateStuBySid()throws Exception{ //通過配置文件獲取配置信息 Reader reader = Resources.getResourceAsReader("config/Configuration.xml"); //構建一個SessionFactory,傳入配置文件 SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader); //獲取session SqlSession session = factory.openSession(); //準備參數對象 Student stu=new Student(); stu.setSid(1); stu.setSname("綠茵"); stu.setSex("女"); //調用刪除方法 int count = session.update("Student.UpdateStuBySid", stu); if(count>0){ System.out.println("修改成功"); }else{ System.out.println("修改失敗"); } //提交 session.commit(); //關閉 session.close(); }
需要在配置文件中添加的是
<!-- 根據SID修改學生信息 --> <update id="UpdateStuBySid" parameterType="entity.Student" > <!-- update Student set sname=#{sname},sex=#{sex} where sid=#{sid} --> update Student <set> <if test="sname!=null"> sname=#{sname}, </if> <if test="sex!=null"> sex=#{sex}, </if> </set> where sid=#{sid} </update>
以上我們就簡單的完成了對Mybatis的增、刪、改、查的基本操作了,關於Mybatis的一些高級內容的講解我會繼續在後中為大家持續講解