使用动态Hibernate登录数据库

3

我需要开发一个应用程序,其中有一个登录功能,可以以管理员身份进入数据库,但不能使用配置文件中的用户名和密码参数。然而我无法实现这个功能,你能帮我吗?

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

}

1个回答

3

方法参数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);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接