hibernate

来源:互联网 发布:中国网络菜市场2017 编辑:程序博客网 时间:2024/05/29 08:39
摘自: http://www.iteedu.com/webtech/j2ee/hibernatediary/4.phpHibernate可以使用XML档案或properties档案来配置SessionFactory,预设的配置文件名称为 hibernate.cfg.xml或hibernate.properties,XML提供较好的结构与配置方式,Hibernate建议使用XML档 案进行配置。 前几个主题中所示范的为使用XML文件的方式,一个XML文件的例子如下: hibernate.cfg.xml true org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost/demo caterpillar 123456 使用XML文件进行配置时,可以在当中指定对象与数据库表格的映像文件位置,XML配置文件的位置必须在Classpath下,使用下面的方式来读入XML文件以配置Hibernate:Configuration config = new Configuration().configure();Configuration的实例管理Hibernate的配置讯息,通常用于建立SessionFactory,例如:SessionFactory sessionFactory = config.buildSessionFactory();SessionFactory一旦建立,就被赋予当时Configuration的配置讯息,之后您改变Configuration并不会影响已建立的 SessionFactory实例,如果对Configuration改动后,则要建立一个新的SessionFactory实例,新的实例中会包括新的 配置讯息。SessionFactory中包括了数据库配置及映像关系,它的建立相当复杂,所以使用时需考虑到重用已建立的SessionFactory实例,SessionFactory是被设计为「执行绪安全的」(Thread-safe)。预设的XML配置文件名称是hibernate.cfg.xml,您也可以自行指定档案,例如:Configuration config = new Configuration().configure("db.cfg.xml"); SessionFactory sf = config.buildSessionFactory();除了使用XML文件进行配置,您也可以使用属性档案进行配置,文件名称是hibernate.properties,一个例子如下: hibernate.propertieshibernate.show_sql = true hibernate.dialect = org.hibernate.dialect.MySQLDialect hibernate.connection.driver_class = com.mysql.jdbc.Driver hibernate.connection.url = jdbc:mysql://localhost/demohibernate.connection.username = caterpillar hibernate.connection.password = 123456hibernate.properties的位置必须在Classpath下,由于properties档案中不包括映像文件的名称,为了要取得对象至数据库表格的映像文件,您必须在程序中如下加载: Configuration cfg = new Configuration() .addClass(onlyfun.caterpillar.User.class) .addClass(onlyfun.caterpillar.Item.class);第一个addClass()加入位于Classpath根目录下的User.hbm.xml,第二个addClass()加入Item类别的映像文件,该 文件必须位于与User类别同一个目录,也就是onlyfun/caterpillar/Item.hbm.xml。在Hibernate下载档案中的etc目录下,有hibernate.cfg.xml与hibernate.properties可供设定参考。
原创粉丝点击