Java 使用hibernate动态登录数据库

Java 使用hibernate动态登录数据库,java,spring,hibernate,login,dao,Java,Spring,Hibernate,Login,Dao,我必须制作一个应用程序,该应用程序具有登录名,以管理员身份进入数据库,而不必使用配置文件的用户名和密码参数,但我无法获取它,您能帮助我吗 public class HibernateUtil { private static SessionFactory sessionFactory; public static void configureHibernateUtil(String user, String pass) { try { Configuration cf

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

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;
}

}

方法参数
user
pass
不会替换
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);
    }
}