org.hibernate.cfg.Configuration實例代表了應用程序到SQL數據庫的配置信息,Configuration對象提供了一個buildSessionFactory()方法,該方法可以產生一個不可變的SessionFactory對象。
另外,先實例化Configuration實例,然后在添加Hiberante持久化類。Configuration對象可調用addAnnotatedClass()方法逐個地添加持久化類,也可調用addPackage()方法添加指定包下的所有持久化類。
創建Configuration對象的方式根據Hibernate配置文件不同而不同:
⊙ 使用hibernate.properties文件作為配置文件
⊙ 使用hibernate.cfg.xml文件作為配置文件
⊙ 不使用任何配置文件,以編碼方式創建Configuration對象
Configuration實例的唯一作用是創建SessionFactory實例,所以它被設計成啟動期間對象,一旦SessionFactory創建完成,它就被丟棄了。
1. 使用hibernate.properties作為配置文件
在Hibernate發布包的project\etc路徑下,提供了一個hibernate.properties文件,該文件愛你詳細列出了Hibernate配置文件的所有屬性。
由於hibernate.properties作為配置文件時,沒有提供添加Hibernate持久化類的方式,因此必須調用Configuration對象的addAnnotatedClass()或addPackage()方法,使用這些方法添加持久化類。
Configuration configuration = new Configuration().addAnnotatedClass(Person.class).addAnnotatedClass(Student.class);
2. 使用hibernate.cfg.xml作為配置文件
使用hibernate.cfg.xml配置文件可以通過<mapping.../>子元素添加Hibernate持久化類,因此無須通過編程方式添加持久化類。
// configure()方法將會負責加載hibernate.cfg.xml文件 Configuration config = new Configuration().configure();
3. 不使用配置文件創建Configuration實例
Configuration對象提供如下方法,通過編程方式創建Configuration實例:
⊙ Configuration addAnnotatedClass(Class annotatedClass) : 用於為Configuration對象添加一個持久化類。
⊙ Configuration addPackage(String packageName) : 用於為Configuration對象添加指定包下的所有持久化類。
⊙ Configuration setProperties(Properties properties) : 用於為Configuration對象設置一系列屬性,這一系列屬性通過Properties實例傳入。
⊙ Configuration setProperty(String propertyName,String value) : 用於為Configuration對象設置一個單獨的屬性。
Class : NewsManager
package hibernate.book._5_4_1._3; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class NewsManager { public static void main(String[] args) { Configuration conf = new Configuration().addAnnotatedClass(News.class) .setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver") .setProperty("hibernate.connection.url", "jdbc:mysql:///hibernate") .setProperty("hibernate.connection.username", "root") .setProperty("hibernate.connection.password", "System").setProperty("hibernate.c3p0.max_size", "20") .setProperty("hibernate.c3p0.min_size", "1").setProperty("hibernate.c3p0.timeout", "5000") .setProperty("hibernate.c3p0.max_statements", "100") .setProperty("hibernate.c3p0.idle_test_period", "3000") .setProperty("hibernate.c3p0.acquire_increment", "2").setProperty("hibernate.c3p0.validate", "true") .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect") .setProperty("hibernate.hbm2ddl.auto", "update"); SessionFactory sessionFactory = conf.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); News news = new News(); news.setTitle("Angel"); news.setContent("Spend all your time waiting for that second chance"); session.save(news); tx.commit(); session.close(); sessionFactory.close(); } }
適合將部分關鍵的配置屬性放在代碼中添加。
啦啦啦