1. 程式人生 > >JavaWeb學習之路——SSM框架之Mybatis(二)

JavaWeb學習之路——SSM框架之Mybatis(二)

1.簡介

框架: 是整個或部分系統的可重用設計,表現為一組抽象構件及構件例項間互動的方法;另一種定義認為,框架是可被應用開發者定製的應用骨架。前者是從應用方面而後者是從目的方面給出的定義。它是一個半成品,一個框架是在一個給定的問題領域內,一個應用程式的一部分設計與實現。

MyBatis 是一款優秀的持久層框架,它支援定製化 SQL、儲存過程以及高階對映。MyBatis 避免了幾乎所有的 JDBC 程式碼和手動設定引數以及獲取結果集。MyBatis 可以使用簡單的 XML 或註解來配置和對映原生資訊,將介面和 Java 的 POJOs(Plain Old Java Objects,普通的 Java物件)對映成資料庫中的記錄。

整體專案框架圖:

2.導包

3.在src下新建全域性配置檔案( 編寫JDBC四個變數)

在全域性配置檔案中引入DTD或schema

Window->preferences->XML->XMLcatlog

新建xml檔案為mybatis.xml,配置jdbc變數

<!DOCTYPE configuration

  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

  "http://mybatis.org/dtd/mybatis-3-config.dtd">

  <configuration>

  <!-- default引用當前環境的id -->

  <environments default="default">

     <environment id="default">

     <!-- 使用事物進行配置jdbc四個變數 -->

     <transactionManager type="JDBC"></transactionManager>

     <dataSource type="POOLED">

     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>

     <property name="url" value="jdbc:mysql://localhost:3306/likui"/>

     <property name="username" value="root"/>

     <property name="password" value="123456"/>

     </dataSource>

     </environment>

  </environments>

  </configuration>

4.新建以mapper結尾的包:在裡面新建mapper.xml配置資料庫sql語句

  編寫需要執行的SQL命令,相當於實現類

<!DOCTYPE mapper

  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  <mapper namespace="com.likui.mapper">

  <!-- id:方法名

       parameterType:定義引數型別

       如果方法返回時list,在resultType中寫list的型別,因為mybatis

       對jdbc封裝,一行一行讀取資料-->

  <select id="selAll" resultType="com.likui.pojo.Flower">

  select * from flower

  </select>

  </mapper>

對應的Flower類:

package com.likui.pojo;

public class Flower {
	private int id;
	private String name;
	private double price;
	private String production;
	public Flower(int id, String name, double price, String production) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.production = production;
	}
	public Flower() {
		super();
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getProduction() {
		return production;
	}
	public void setProduction(String production) {
		this.production = production;
	}
	
}

資料庫表結構:

5.測試結果(只有在單獨使用mybatis時使用,最後在ssm中不需要)

mybatis可以自動對映,將資料庫表中欄位值名稱和類中實體名寫成一致形式

package com.likui.pojo;

public class Mybatis {

     public static void main(String[] args) throws IOException {

           InputStream is = Resources.getResourceAsStream("mybatis.xml");

           //使用工廠設計模式

           SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

           //生產SqlSession

           SqlSession session=factory.openSession();

           List<Flower> list = session.selectList("a.b.selAll");

           System.out.println("id\t\tname\t\tprice\t\tproduction");

           for (Flower flower : list) {

                         System.out.println(flower.getId()+"\t\t"+flower.getName()+"\t\t"+

           flower.getPrice()+"\t\t"+flower.getProduction());

           }

           session.close();

     }

}

6.實現JDBC tomcat Pool步驟

UNPOOLED– 這個資料來源的實現只是每次被請求時開啟和關閉連線。雖然有點慢,但對於在資料庫連線可用性方面沒有太高要求的簡單應用程式來說,是一個很好的選擇。 不同的資料庫在效能方面的表現也是不一樣的,對於某些資料庫來說,使用連線池並不重要,這個配置就很適合這種情形。UNPOOLED 型別的資料來源僅僅需要配置以下 5 種屬性:

  • driver – 這是 JDBC 驅動的 Java 類的完全限定名(並不是 JDBC 驅動中可能包含的資料來源類)。
  • url – 這是資料庫的 JDBC URL 地址。
  • username – 登入資料庫的使用者名稱。
  • password – 登入資料庫的密碼。
  • defaultTransactionIsolationLevel – 預設的連線事務隔離級別。
  • 作為可選項,你也可以傳遞屬性給資料庫驅動。要這樣做,屬性的字首為“driver.”,例如:
  • driver.encoding=UTF8
  • 這將通過 DriverManager.getConnection(url,driverProperties) 方法傳遞值為 UTF8 的 encoding 屬性給資料庫驅動。

POOLED– 這種資料來源的實現利用“池”的概念將 JDBC 連線物件組織起來,避免了建立新的連線例項時所必需的初始化和認證時間。 這是一種使得併發 Web 應用快速響應請求的流行處理方式。

JNDI – 這個資料來源的實現是為了能在如 EJB 或應用伺服器這類容器中使用,容器可以集中或在外部配置資料來源,然後放置一個 JNDI 上下文的引用。這種資料來源配置只需要兩個屬性:

  • initial_context – 這個屬性用來在 InitialContext 中尋找上下文(即,initialContext.lookup(initial_context))。這是個可選屬性,如果忽略,那麼 data_source 屬性將會直接從 InitialContext 中尋找。
  • data_source – 這是引用資料來源例項位置的上下文的路徑。提供了 initial_context 配置時會在其返回的上下文中進行查詢,沒有提供時則直接在 InitialContext 中查詢。

7.全域性配置檔案

<transactionManager/>

type屬性可選值 :

  • JDBC – 這個配置就是直接使用了 JDBC 的提交和回滾設定,它依賴於從資料來源得到的連線來管理事務作用域。
  • MANAGED – 這個配置幾乎沒做什麼。它從來不提交或回滾一個連線,而是讓容器來管理事務的整個生命週期(比如 JEE 應用伺服器的上下文)。 預設情況下它會關閉連線,然而一些容器並不希望這樣,因此需要將 closeConnection 屬性設定為 false 來阻止它預設的關閉行為。

資料來源(dataSource)

dataSource 元素使用標準的 JDBC 資料來源介面來配置 JDBC 連線物件的資源。

許多 MyBatis 的應用程式會按示例中的例子來配置資料來源。雖然這是可選的,但為了使用延遲載入,資料來源是必須配置的。

有三種內建的資料來源型別(也就是 type=”[UNPOOLED|POOLED|JNDI]”):

*8.使用資料庫連線池:在記憶體中開闢一塊空間,存放多個數據庫連線物件。JDBC Tomcat Pool,直接由tomacat產生資料庫連線池,有active、idle狀態,使用資料庫連線池的目的,在高頻率訪問資料庫時,使用資料庫連線池可以降低伺服器系統壓力,提升程式執行效率,適用於大型專案。

條件:lib下有資料庫驅動檔案、META-INF下context.xml檔案、src下有serverlet檔案

(1)在context.xml中設定資料連線的相關資訊

<Context>

<Resource driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/likui"

username="root" password="123456" maxActive="50" maxIdle="20" name="test"

auth="Container" maxWait="10000"  type="javax.sql.DataSource"/>

</Context>

(2)在src下新建serverlet檔案,用於獲取資料庫連線資訊並執行

@WebServlet("/pool")

public class Demoserverlet extends HttpServlet {

     @Override

     protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

           try {

                Context cxt = new InitialContext();

                DataSource ds = (DataSource) cxt.lookup("java:comp/env/test");  //test是連線的名稱

                Connection conn = ds.getConnection();

                PreparedStatement ps = conn.prepareStatement("select * from flower");

                ResultSet rs = ps.executeQuery();

                res.setContentType("text/html;charset=utf-8");

                PrintWriter out = res.getWriter();

                while(rs.next()){

                     out.print(rs.getInt(1)+"&nbsp;&nbsp;&nbsp;&nbsp;"+rs.getString(2)+"<br/>");

                }

                out.flush();

                out.close();

                rs.close();

           } catch (NamingException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

           } catch (SQLException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

           }

     }

}

效果圖如下所示:

*9.三種查詢方式

(1)selectList():返回值為一個list型別,適用於遍歷查詢所有結果的需求

xmll配置檔案 中: 

<select id="selAll" resultType="com.likui.pojo.Flower">

  select * from flower

  </select>

java檔案中:

List<Flower> list = session.selectList("a.b.selAll");

          System.out.println("id\t\tname\t\tprice\t\tproduction");

           for (Flower flower : list) {

                System.out.println(flower.getId()+"\t\t"+flower.getName()+"\t\t"+

           flower.getPrice()+"\t\t"+flower.getProduction());

           }

(2)selectOne(),:返回值為一個object物件,適用於返回結果只是一個變數或一行資料時

xml配置檔案中:

  <select id="selById" resultType="int">

   select count(*) from flower where id=1

  </select>

java檔案中:

int count=session.selectOne("a.b.selById");

System.out.println(count);

(3)selectMap():返回值時Map,適用於需求在查詢結果中通過某列值取得相應值

xml配置檔案 中: 

 <select id="c" resultType="com.likui.pojo.Flower">

  select * from flower

  </select>

Java檔案中:

Map<Object,Object> map=session.selectMap("a.b.c", "name");

System.out.println(map);

注:帶*號為可選操作