Sas*_*wat 21 configuration hibernate
我不想拥有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();
}
Run Code Online (Sandbox Code Playgroud)
我尝试过上述方法.但我面临的问题是,hibernate抛出一个异常说" ./hibernate.cfg.xml file missing".
保留hibernate.cfg.xml文件真的是强制性的吗?
提前致谢
Swa*_*rma 23
我相信这是因为你configure()对这个Configuration对象的召唤.尝试删除它,休眠不会查找不存在的文件.基本上你是通过你的properties对象设置所有必需的属性,所以没有必要告诉Hibernate寻找一个hibernate.cfg.xml文件,这正是该configure()方法的作用.
小智 14
不,我不认为配置xml是强制性的.为了解决您的问题,我认为您需要使用org.hibernate.cfg.Configuration类.看看这个链接:http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html
基本上,你需要像这样的东西
Configuration cfg = new Configuration()
.setProperty("hibernate.dialect", "com.mysql.jdbc.Driver")
.setProperty("hibernate.connection.datasource", "jdbc:mysql://localhost:3306/books")
.setProperty("hibernate.order_updates", "true");
Run Code Online (Sandbox Code Playgroud)
然后创建你的sessionFactory,你只需说,cfg.buildSessionFactory();
不,使用hibernate.cfg.xml并不是必须的.只是不要使用.configure().如果我们使用Hibernate将寻找hibernate.cfg.xml .configure().
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17833 次 |
| 最近记录: |