資料庫連接池技術的基本原理:
由Web容器(如Tomcat)提供資料來源對象,在程式中使用 JNDI 技術獲得該對象。一般如果自己建立串連的話,用下面的代碼擷取資料來源對象:
Context context = new InitialContext();
DataSource dataSource = (DataSource)context.lookup("java://comp/env/jdbc/mydb");
Connection conn = dataSource.getConnection();
這裡mydb是要串連到的資料庫名,一定要注意 java: 後面有雙斜線,否則就會報出異常:
org.hibernate.service.jndi.JndiException:Unable to lookup JNDI name java:comp/env...
但其實如果使用Hibernate架構的話,就不用這樣費事了。按照下面的步驟一步步來就OK了:
1. 找到tomcat安裝目錄,以 D:\Program Files\Apache Software Foundation\Tomcat 6.0\conf 為例,在 context.xml 檔案中的<Context>標籤下添加代碼:
1 <!--Resource 設定資料庫連接池的核心-->2 <!--屬性 name 資料來源的名字 屬性 auth 表示驗證方式 type 資源的類型 --> 3 <Resource name="jdbc/struts" auth="Container" type="javax.sql.DataSource"4 maxActive="100" maxIdle="30" maxWait="10000"5 username="root" password="****"6 driverClassName="com.mysql.jdbc.Driver"7 url="jdbc:mysql://192.168.1.173:3306/struts"/>
我的資料庫名稱為struts,所以這裡配置的名字也是struts。
2. 將JDBC的驅動jar包放到 tomcat 的 lib 檔案夾下,如 D:\Program Files\Apache Software Foundation\Tomcat 6.0\lib。
3. 在項目的 web.xml 檔案中添加如下代碼:
1 <resource-ref>2 <description>struts datasource</description>3 <res-ref-name>jdbc/struts</res-ref-name>4 <res-type>javax.sql.DataSource</res-type>5 <res-auth>Container</res-auth>6 </resource-ref>
這裡的各配置要和在 context.xml 檔案中的配置一致。
4. 配置 hibernate.cfg.xml。可以使用視圖直接選擇 Use JNDI DataSource 選項,然後在DataSource欄中填入 "java://comp/env/jdbc/struts"。產生的程式碼:
1 <?xml version='1.0' encoding='UTF-8'?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 <!-- Generated by MyEclipse Hibernate Tools. --> 6 <hibernate-configuration> 7 8 <session-factory> 9 <property name="connection.datasource">10 java://comp/env/jdbc/struts11 </property>12 <property name="dialect">13 org.hibernate.dialect.MySQLDialect14 </property>15 16 <property name="show_sql">true</property>17 18 <mapping resource="com/entity/Users.hbm.xml" />19 </session-factory>20 21 </hibernate-configuration>
5. 使用MyEclipse外掛程式添加的Hibernate架構的話,會產生一個 HibernateSessionFactory 類,直接調用這個類的靜態函數 getSession() 就能擷取到 Session 的一個執行個體。接下來的操作就跟沒使用串連池是一樣的了。