HIbernate 独立项目通过properties配置数据库

废话不多说开始正题:

HIbernate 独立项目通过properties配置数据库

建立资源文档:

#定义方言(定义优化的sql语句)使用JDNI初始化数据库很重要
hibernate.dialect=org.hibernate.dialect.SQLServerDialect
hibernate.connection.driver_class=com.microsoft.sqlserver.jdbc.SQLServerDriver
hibernate.connection.url=jdbc:sqlserver://localhost:1433;DatabaseName=Test
hibernate.connection.username=sa
hibernate.connection.password=769170594
#表示是否输出操作数据库的语句
hibernate.show_sql=true
#表示是个格式化输出sql语句
hibernate.format_sql=true
#表示是否根据映射文件自动创建数据库表
#hibernate.hbm2ddl.auto=update
然后阅读hibernate文档发现有
configuration.setProperties(properties);此方法。
所以可以列出如下代码来获取资源文件从而配置数据库:
public class HibernateUtil {
    private static SessionFactory ourSessionFactory;

    public static Session getSession() throws HibernateException {
        //单独使用Hibernate通过properties配置数据库
        Configuration configuration = new Configuration().configure();
        InputStream in = HibernateUtil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        configuration.setProperties(properties);
       // ourSessionFactory=new Configuration().configure().buildSessionFactory();
        ourSessionFactory = configuration.buildSessionFactory();
        return ourSessionFactory.openSession();
    }
}