关于hibernate.properties和hibernate.cfg.xml的分析

来源:互联网 发布:电子招投标系统源码 编辑:程序博客网 时间:2024/04/28 08:50
很多朋友不知道两者的区别,我在这里详细说说吧。
如果是使用hibernate.properties作为配置文件的话,配置文件的内容大概是这样的:
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/work
hibernate.connection.username=root
hibernate.connection.password=1234
hibernate.show_sql=true
而我们想用hibernate.cfg.xml的话,内容大概是这样的:
<hibernate-configuration>
        <session-factory>
                <property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
                <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
                <property name="connection.url">jdbc:mysql://localhost:3306/work</property>
                <property name="connection.username">root</property>
                <property name="connection.password">1234</property>
                <mapping resource="bean/Note.hbm.xml"/>
                <mapping resource="bean/User.hbm.xml"/>
        </session-factory>
</hibernate-configuration>
大家有没有发现什么不同的地方呢?对了,以hibernate.properties配置的话,没有配置被映射的类。那hibernate不能在hibernate.properties中知道需要映射的类,在哪里我们能让它知道呢?答案就在源文件里了。
      当我们使用hibernate.properties作为配置文件的时候,我们的源文件中需要这样构造一个config:
               Configuration config = new Configuration();
              config.addClass(User.class).addClass(Note.class);
              SessionFactory sf = config.buildSessionFactory();
              Session session = sf.openSession();
这里的config我们必须调用addClass()方法,这就是我们使hibernate知道映射类的地方了。当然使用hibernate.cfg.xml来配置的话,我们就可以这样写:
               Configuration config = new Configuration();
              SessionFactory sf = config.configure("/hibernate.cfg.xml").buildSessionFactory();
               //这里调用了configure()方法来指定hibernate.cfg.xml的位置
              Session session = sf.openSession();
        我们就不用再配置需要映射的类了,重复配置的话会出现重复映射异常。
        总之,我们要使用两种方法其中一种就行了,就是说如果hibernate.cfg.xml中没有说明映射关系的话,在源文件中使用addClass()方法就可以了,但不能重复!。
        另外,在hibernate的启动过程中,会先找hibernate.properties,然后读取hibernate.cfg.xml,后者会覆盖前者相同的属性。  
原创粉丝点击