Dynamically log into database with hibernation

I need to make an application that has a login to login to the database as an administrator, without having to use the username and password parameters of the config file, but I can't get it, can you please help me?

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

      

}

+3


source to share


1 answer


Method parameter user

and pass

does NOT change properties cfg

. So the method doesn't work. Here's the modified code:



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

      

+2


source







All Articles