在持久层领域中框架已经有多了.现在最流行的是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: MailObjPersistcfg.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); }} 原文链接: