XML文件和properties文件的异同

如果是使用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:

这个方法用静态的方法修饰,或者放在构造函数中。

Java代码 

static{  
     try{  
      // Create a configuration based on the properties file we've put  
       Configuration config = new Configuration();  
       config.addClass(Company.class)  
             .addClass(HourlyEmployee.class)  
             .addClass(SalariedEmployee.class);  
      // Get the session factory we can use for persistence  
      sessionFactory = config.buildSessionFactory();  
    }catch(Exception e){e.printStackTrace();}  
  
  }  

这里的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.properties 文件是默认读取的。
        另外,在hibernate的启动过程中,会先找hibernate.properties,然后读取hibernate.cfg.xml,后者会覆盖前者相同的属性


猜你喜欢

转载自blog.csdn.net/qq_39917089/article/details/80457691
今日推荐