hibernate.properties 文件与hibernate.cfg.xml文件的区别

很多朋友不知道两者的区别,我在这里详细说说吧。
如果是使用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:

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

    

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,后者会覆盖前者相同的属性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值