在程序中设置hibernate configuration的Property



文章分类:综合技术
在程序中设置hibernate configuration的Property
2009-08-01 20:26
在使用Hibernate时一般都会编写一个hibernate.cfg.xml文件,并在其中配置一些连接数据库的属性。这在很多情况下都是非常合适的,但是如果需要动态获得数据库链接信息,这种方法就不行了。假设我们要根据用户的输入信息连接响应的数据库,该怎么办呢?

我们都知道,Hibernate的SessionFactory是通过Configuration获得的,hibernate.cfg.xml文件中配置很多信息都对应为Configuration的Property,因此只要可以为Configuration设置属性并添加hbm.xml信息,就可以动态的获得SessionFactory了。具体代码如下:

Properties jdbcPros = new Properties();
jdbcPros.setProperty("hibernate.connection.useUnicode", "true");
jdbcPros.setProperty("hibernate.connection.characterEncoding", "UTF-8");
jdbcPros.setProperty("hibernate.connection.driver_class", "org.gjt.mm.mysql.Driver");
jdbcPros.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/your_db");
jdbcPros.setProperty("hibernate.connection.username", "root");
jdbcPros.setProperty("hibernate.connection.password", "your_pw");
jdbcPros.setProperty("hibernate.dialect", "net.sf.hibernate.dialect.MySQLDialect");
jdbcPros.setProperty("hibernate.show_sql", "false");
jdbcPros.setProperty("hibernate.use_outer_join", "true");
jdbcPros.setProperty("hibernate.transaction.factory_class", "net.sf.hibernate.transaction.JTATransactionFactory");

Configuration cfg = new Configuration();
cfg.setProperties(jdbcPros);

try {
    cfg.addFile("A.hbm.xml");
    cfg.addFile("B.hbm.xml");
} catch (MappingException e) {
    e.printStackTrace();
}

try {
    SessionFactory sessionFactory = cfg.buildSessionFactory();
} catch (HibernateException e) {
    e.printStackTrace();

你可能感兴趣的:(sql,Hibernate,mysql,xml,.net)