如何使用hibernate.properties文件而不是hibernate.cfg.xml

我正在尝试使用Hibernate连接到servlet中的数据库。我已经读过我们可以使用hibernate.cfg.xml或hibernate.properties文件来配置session.For我使用xml。 现在,当我尝试使用属性而不是xml时,它无法正常工作。 这是说没有找到 hibernate.cfg.xml 。但是我提到使用xml文件并且事实上我已经删除了那个xml文件。

请帮我。 如果我做错了,请纠正我。

根据我对hibernate的理解,最好的办法是在hibernate.cfg.xml文件和hibernate.cfg.xml其他配置中定义映射。

另一种配置方法是在名为hibernate.cfg.xml的文件中指定完整配置。 此文件可用作hibernate.properties文件的替代文件,如果两者都存在,则可用于覆盖属性。

一旦必须调整Hibernate缓存, hibernate.cfg.xml也会更方便。 您可以选择使用hibernate.properties或hibernate.cfg.xml 。 两者都是等价的。

您可以在以下链接中阅读有关此内容的更多信息:

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html

此代码默认调用hibernate.cfg.xml:

 Configuration configuration = new Configuration().configure(); 

这段代码默认会调用hibernate.properties:

 Configuration configuration = new Configuration(); 

希望能帮助到你。

如果您正在使用servlet中数据库 ,那么您应该在服务器中定义一个DataSource并指向一个hibernate属性,而不是通过您现在可能正在使用的所有其他hibernate属性来定义所有内容。

这样做的好处是允许您独立于应用程序定义连接池和其他连接相关参数。

例如,您的生产环境可能具有与测试和开发环境不同的数据库密码。

如果您使用的是hibernate.properties删除.configure() 。 下面的代码是HibernateUtil会话工厂实现。

 private static SessionFactory buildSessionFactory() { try { Configuration configuration = new Configuration(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); configuration.addAnnotatedClass(LookUpModel.class); return configuration .buildSessionFactory(serviceRegistry); }catch(Exception e) { e.printStackTrace(); throw new RuntimeException("There is issue in hibernate util"); } } 

hibernate.properites文件

 hibernate.connection.driver_class = com.mysql.jdbc.Driver hibernate.connection.url = jdbc:mysql://localhost:3306/test hibernate.connection.username = root hibernate.connection.password = passsword hibernate.c3p0.min_size=5 hibernate.c3p0.max_size=20 hibernate.c3p0.timeout=1800 hibernate.c3p0.max_statements=50 hibernate.dialect = org.hibernate.dialect.MySQL5Dialect