使用hibernate动态登录数据库

Login into database with hibernate dynamically

我必须创建一个应用程序,该应用程序具有以管理员身份进入数据库的登录名,而不必使用配置文件的用户名和密码参数,但我无法获取,你能帮我吗?

public class HibernateUtil {

private static SessionFactory sessionFactory;

public static void configureHibernateUtil(String user, String pass) {
    try {
        Configuration cfg = new Configuration();
        cfg.configure("/dao/hibernate.cfg.xml"); //hibernate config xml file name
        String newUserName = null, newPassword = null;//set them as per your needs
        cfg.getProperties().setProperty("hibernate.connection.password", newPassword);
        cfg.getProperties().setProperty("hibernate.connection.username", newUserName);
        //In next line you just tell Hibernate which classes are you going to query

        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties());
        sessionFactory = cfg.buildSessionFactory(ssrb.build());
    } catch (HibernateException he) {
        System.err.println("Ocurrió un error en la inicialización de la SessionFactory: " + he);
        throw new ExceptionInInitializerError(he);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

}

方法参数 userpass 不会 替换 cfg 的属性。所以该方法不起作用。这是修改后的代码:

public static void configureHibernateUtil(String user, String pass) {
    try {
        Configuration cfg = new Configuration();
        cfg.configure("/dao/hibernate.cfg.xml"); //hibernate config xml file name
        //String newUserName = null, newPassword = null;//set them as per your needs
        cfg.getProperties().setProperty("hibernate.connection.password", pass);
        cfg.getProperties().setProperty("hibernate.connection.username", user);
        //In next line you just tell Hibernate which classes are you going to query

        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties());
        sessionFactory = cfg.buildSessionFactory(ssrb.build());
    } catch (HibernateException he) {
        System.err.println("Ocurrió un error en la inicialización de la SessionFactory: " + he);
        throw new ExceptionInInitializerError(he);
    }
}