2010年9月16日 星期四

在Hibernate中Config Connection Pool

今天試著在Hibernate中Config Connection Pool時發現 Hibernate3.3.1 GA版裡面,已經將C3P0ConnectionProvider這個class搬到 hibernate-c3p0-3.3.1.GA.jar這個Jar中了,可以到這個網址下載http://www.java2s.com/Code/Jar/GHI/Downloadhibernatec3p0331GAjar.htm

把它加到build path後,編輯persistence.xml。Mark紅色的部分,即為新增的Connection Pool設定。

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="Test">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
            <properties>
                <property name="hibernate.connection.driver_class" value="com.ibm.db2.jcc.DB2Driver"/>
                <property name="hibernate.connection.password" value="db2admin"/>
                <property name="hibernate.connection.url" value="jdbc:db2://localhost:50000/puli"/>
                <property name="hibernate.connection.username" value="db2admin"/>
                <property name="hibernate.default_schema" value="db2admin"/>
                <property name="hibernate.dialect" value="org.hibernate.dialect.DB2Dialect"/>
                    <!--使用c3p Connection Pool -->
                <property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" />
                <property name="hibernate.c3p0.max_size" value="100" />
                <property name="hibernate.c3p0.min_size" value="3" />
                <property name="hibernate.c3p0.acquire_increment" value="1" />
                <property name="hibernate.c3p0.idle_test_period" value="300" />
                <property name="hibernate.c3p0.max_statements" value="0" />
                <property name="hibernate.c3p0.timeout" value="100" />
            </properties>
    </persistence-unit>
</persistence>

回到使用JPA的程式碼,假設在以下的程式碼中,在把程式由原本的standalone轉成使用connection pool後,不能在程式碼裡面呼叫JPAUtil.shutdown()這個方法,因為這個方法會把connection中斷。

public class PuliTest {
    public static void main(String[] args) {
        EntityManager newEntityManager =
        JPAUtil.getEntityManagerFactory().createEntityManager();
        EntityTransaction newEtx = newEntityManager.getTransaction();
        newEtx.begin();
        PatientBasicInfo patient = (PatientBasicInfo) newEntityManager.find(PatientBasicInfo.class, "12345");
        System.out.println(patient.getPatientfirstname());
        System.out.println(patient.getPatientlastname());
        System.out.println(patient.getPatientaddress());
        newEtx.commit();
        newEntityManager.close();
        //JPAUtil.shutdown(); 在使用connection pool的程式中,需 comment掉此method call
    }
}

沒有留言:

張貼留言