hibernate配置並測試是否可以連線資料庫
阿新 • • 發佈:2019-01-05
1.配置hibernate.cfg.xml檔案(以mysql為例)。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <!-- 配置連線資訊 --> <!-- hibernate.connection.driver_class jdbc驅動類 hibernate.connection.url jdbc URL hibernate.connection.username 資料庫使用者 hibernate.connection.password 資料庫使用者密碼 hibernate.connection.pool_size 連線池容量上限數目 hibernate.dialect org.hibernate.dialect.MySQLDialect 資料庫方言 --> <session-factory> <!-- 必選配置 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/資料庫名稱</property> <property name="hibernate.connection.username">資料庫賬號</property> <property name="hibernate.connection.password">資料庫密碼</property> <!-- 資料庫方言 使用的資料庫型別 --> <property name="hibernate.dialect org.hibernate.dialect.MySQLDialect"></property> <!-- 可選配置 --> <!-- 對映檔案 --> </session-factory> </hibernate-configuration>
2.寫測試類測試是否能連線資料庫(引入junit4)。
右鍵方法測試。import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.junit.Test; public class TestConnection { @Test public void testConn() { //讀取hibernate.cfg.xml中的配置資訊 Configuration config = new Configuration(); config.configure(); //獲取資料庫的連線池 SessionFactory factory = config.buildSessionFactory(); System.out.println(factory); } }