[原创]Pro Hibernate 3笔记和小结(8)之第三章创建简单应用

王朝other·作者佚名  2006-07-06
窄屏简体版  字體: |||超大  

/**

作者:Willpower

来源:Rifoo Technology(http://www.rifoo.com

时间:2006-07

备注:转载请保留以上声明

**/

今天我们接着学习第三章创建简单应用,上一篇讲到了Hibernate配置文件的创建,我们创建了XML格式的配置文件。当然,正如前面的学习中我们知道,Hibernate还提供了另一种property文件的方式来存放配置信息。

创建一个普通的java property文件,内容大致如下:

CODE:

hibernate.connection.driver_class=org.hsqldb.jdbcDriver

hibernate.connection.url=jdbc:hsqldb:hsql://localhost/hibernate

hibernate.connection.username=sa

hibernate.connection.password=

hibernate.pool_size=5

hibernate.show_sql=false

hibernate.dialect= org.hibernate.dialect.HSQLDialect

[Copy to clipboard]

大家注意到了,它并没有包含xml映射资源,实际上,我们不能在property文件中包含此类映射信息。我们需要在Configuration类中去做这方面的映射,以下是简单清单:

CODE:

Configuration config = new Configuration();

config.addClass( Motd.class );

config.setProperties( System.getProperties() );

SessionFactory sessions = config.buildSessionFactory();

[Copy to clipboard]

注意:Configuration对象会在classpath中去查找映射文件,它会在和类相同命名的包中去查找。因为我们的类的全名为book.hibernate.gettingstarted.Motd,所以我们从classpath根路径下看到以下成对文件,一个类,一个hbm xml映射文件,如下所示:

/book/hibernate/gettingstarted/Motd.class

/book/hibernate/gettingstarted/Motd.hbm.xml

当然,如果我们想手动更改配置文件的目录,我们需要将它们以资源的形式添加到Configuration对象中,如下所示:

CODE:

Configuration config = new Configuration();

config.addResource( "config/Motd.hbm.xml" );

config.setProperties( System.getProperties() );

SessionFactory sessions = config.buildSessionFactory();

[Copy to clipboard]

在实例中,可能会有更多的配置文件存在,然而,有一种方便的做法可以方面我们管理配置文件。就是我们将类和它的映射文件放在同一个目录中,并且它们的命令最好也是类似或相同的,比如Motd.hbm.xml文件是映射Motd类的,它们都在同一个包(目录)下面。这种方式使得我们可以快速查找任何想要的类映射,并且保持了映射文件的可读性。

如果你不想使用一个文件来提供配置信息,还有第三种方式,那就是直接在命令行中使用-D标志。例如:

CODE:

java -classpath ...

-Dhibernate.connection.driver_class=org.hsqldb.jdbcDriver

-Dhibernate.connection.url=jdbc:hsqldb:hsql://localhost/hibernate

-Dhibernate.connection.username=sa

-Dhibernate.connection.password=

-Dhibernate.pool_size=5

-Dhibernate.show_sql=false

-Dhibernate.dialect= org.hibernate.dialect.HSQLDialect

org.hibernate.tool.hbm2ddl.SchemaExport

--output=advert.sql

/book/hibernate/gettingstarted/Motd.hbm.xml

[Copy to clipboard]

这种方式可能是三种方式中最直接的,它有时会很有用。

但是对于大多数情况,我们强烈推荐使用xml格式的配置文件,它是最好的选择。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航