提供JDBC連接

来源:百度文库 编辑:神马文学网 时间:2024/04/24 14:29:34
如果需要的話,您可以自行提供JDBC連接物件給Hibernate使用,而無需透過配置文件設定JDBC來源,一個最簡單的例子如下:
Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql://localhost:3306/HibernateTest?user=root&password=";java.sql.Connection conn = DriverManager.getConnection(url);SessionFactory sessionFactory = cfg.buildSessionFactory();Session session = sessionFactory.openSession(conn);
當然您也可以透過屬性文件hibernate.properties來配置JDBC來源,例如:
hibernate.properties
hibernate.show_sql = truehibernate.dialect = net.sf.hibernate.dialect.MySQLDialecthibernate.connection.driver_class = com.mysql.jdbc.Driverhibernate.connection.url = jdbc:mysql://localhost/HibernateTesthibernate.connection.username = caterpillarhibernate.connection.password = 123456
如果是透過XML文件hibernate.cfg.xml則是如下進行配置:
hibernate.cfg.xml
true net.sf.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost/HibernateTest caterpillar 123456
Hibernate在資料庫連接池的使用上是可選的,您可以使用C3P0連接池,當您的屬性文件中含有hibernate.c3p0.*的配置時,就會自動啟用C3P0連接池,而您的CLASSPATH中必須包括c3p0-0.8.4.5.jar,屬性文件hibernate.properties的配置範例如下:
hibernate.properties
hibernate.show_sql = truehibernate.dialect = net.sf.hibernate.dialect.MySQLDialecthibernate.connection.driver_class = com.mysql.jdbc.Driverhibernate.connection.url = jdbc:mysql://localhost/HibernateTesthibernate.connection.username = roothibernate.connection.password =hibernate.c3p0.min_size=5hibernate.c3p0.max_size=20hibernate.c3p0.timeout=1800hibernate.c3p0.max_statements=50
如果是使用hibernate.cfg.xml配置C3P0連接池的例子如下:
hibernate.cfg.xml
true net.sf.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost/HibernateTest root 5 20 1800 50
您也可以使用Proxool或DBCP連接池,只要在配置文件中配置hibernate.proxool.或hibernate.dbcp. 等相關選項,這可以在hibernate的etc目錄中找hibernate.properties中的配置例子來參考,當然要記得在CLASSPATH 中加入相關的jar檔案。
如果您使用Tomcat的話,您也可以透過它提供的DBCP連接池來取得連接,您可以先參考這邊的文章來設定Tomcat的DBCP連接池:
DBCP連接池設定
設定好容器提供的DBCP連接池之後,您只要在配置文件中加入connection.datasource屬性,例如在hibernate.cfg.xml中加入:
hibernate.cfg.xml
java:comp/env/jdbc/dbname
如果是在hibernate.properties中的話,則加入:
hibernate.properties
hibernate.connection.datasource = java:comp/env/jdbc/dbname