在持久層領域中框架已經有多了.現在最流行的是hibernate,用了之後,很不錯,給人一種舒服感,就象當初第一次用JDO時的感覺.
用了一段時間後,總結看發現在配置方面給我留有一點影響:衆所周知,hibernate使用兩種格式的配置文件,就是屬性文件和XML文件,
在程序中構造會話工廠時,使用了xml格式,如果想使用屬性文件,卻不知道如何配置,現在回頭仔細看了看,原來是這樣:
不管是hibernate的2.x還是3.x,配置方法都沒有變化.
測試環境:jbuilder2005,hibernate2.18以及hibernate3.05.
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;
public class TestHbCfg{
private SessionFactory sessions;
public TestHbCfg(){
}
public void test(){
try {
this.configure();
}
catch (HibernateException ex) {
ex.printStackTrace();
}
}
/**
* 在這個Configuration實例中沒有調用configure方法,該類缺省使用屬性文件.
* @throws HibernateException
*/
public void configure1() throws HibernateException {
sessions = new Configuration()
.addClass(MailObjPersist.class)
.buildSessionFactory();
}
/**
* 首先實例化一個Configuration對象,然後調用了configure()方法,注意調用的是不帶參數的這個方法.
* 這樣它就會在類路徑的根下查找hibernate.cfg.xml.
* @throws HibernateException
*/
public void configure2() throws HibernateException {
Configuration cfg=new Configuration();
cfg.configure();
sessions = cfg.buildSessionFactory();
}
/**
*
* @throws HibernateException
*/
public void configure() throws HibernateException {
Configuration cfg=new Configuration();
//爲類MailObjPersist添加影射文件.如果在hibernate.cfg.xml中已經配置了這個類的射文件,就不要在代碼中添加了.
//如果添加,將會得到一個異常:net.sf.hibernate.MappingException: duplicate import: MailObjPersist
cfg.addClass(MailObjPersist.class);
cfg.configure();//"hibernate.cfg.xml"
sessions = cfg.buildSessionFactory();
}
/**
* SchemaExport工具類,該類能在程序中使用,它的方法create(boolean script,boolean export);
* script -爲true就把根據對象關係影射生成的DDL輸出到控制檯,export -爲true,就在目標數據庫執行DDL進行創建
* @throws HibernateException
*/
public void exportTables() throws HibernateException {
Configuration cfg = new Configuration().addClass(MailObjPersist.class);
new SchemaExport(cfg).create(true, true);
}
/**
* execute(boolean script, boolean doUpdate)
* script -爲true就把根據對象關係影射生成的DDL輸出到控制檯,doUpdate -爲true,就在目標數據庫執行DDL進行更新
*/
public void updateTables(){
Configuration cfg = new Configuration();
cfg.addClass(Broad.class);
SchemaUpdate su=new SchemaUpdate(cfg);
su.execute(true,true);
}
}