我不想要hibernate.cfg.xml文件。相反,我希望通过我的代码完成所有配置,如下所示。
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
文件真的是强制性的吗?
提前感谢
发布于 2012-01-12 13:18:55
我相信这是因为您对Configuration
对象进行了configure()
调用。尝试删除它,hibernate将不会查找不存在的文件。基本上,您是通过properties
对象设置所有必需的属性,因此不需要告诉Hibernate查找hibernate.cfg.xml
文件,而这正是configure()
方法所做的。
发布于 2015-10-12 00:25:15
不,使用hibernate.cfg.xml不是强制性的。只要不使用.configure()
即可。如果我们使用.configure()
,Hibernate将查找hibernate.cfg.xml。
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;
}
}
https://stackoverflow.com/questions/8830357
复制相似问题