首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >是否必须使用hibernate.cfg.xml文件进行配置

是否必须使用hibernate.cfg.xml文件进行配置
EN

Stack Overflow用户
提问于 2012-01-12 13:01:51
回答 2查看 19.5K关注 0票数 21

我不想要hibernate.cfg.xml文件。相反,我希望通过我的代码完成所有配置,如下所示。

代码语言:javascript
复制
private static final SessionFactory factory;
private static final Properties properties;

static
{
    properties = new Properties();
    properties.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
    properties.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/books");
    properties.setProperty("hibernate.connection.username", "jhtp7");
    properties.setProperty("hibernate.connection.password", "password");
    properties.setProperty("hibernate.show_sql", "com.mysql.jdbc.Driver");
    properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");

    factory = new Configuration().setProperties(properties).configure().
                            buildSessionFactory();
}

我已经尝试过上述方法。但我面临的问题是hibernate抛出了一个异常,写着"./hibernate.cfg.xml file missing“。

保留hibernate.cfg.xml文件真的是强制性的吗?

提前感谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-12 13:18:55

我相信这是因为您对Configuration对象进行了configure()调用。尝试删除它,hibernate将不会查找不存在的文件。基本上,您是通过properties对象设置所有必需的属性,因此不需要告诉Hibernate查找hibernate.cfg.xml文件,而这正是configure()方法所做的。

票数 24
EN

Stack Overflow用户

发布于 2015-10-12 00:25:15

不,使用hibernate.cfg.xml不是强制性的。只要不使用.configure()即可。如果我们使用.configure(),Hibernate将查找hibernate.cfg.xml。

代码语言:javascript
复制
public class HibernateUtil {
    private static SessionFactory sessionFactory ;
    static {
        Configuration configuration = new Configuration();

        configuration.addAnnotatedClass (org.gradle.Person.class);
        configuration.setProperty("hibernate.connection.driver_class","com.mysql.jdbc.Driver");
        configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");                                
        configuration.setProperty("hibernate.connection.username", "root");     
        configuration.setProperty("hibernate.connection.password", "root");
        configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        configuration.setProperty("hibernate.hbm2ddl.auto", "update");
        configuration.setProperty("hibernate.show_sql", "true");
        configuration.setProperty(" hibernate.connection.pool_size", "10");

        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
        sessionFactory = configuration.buildSessionFactory(builder.build());
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
} 
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8830357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档