我正在实现一个Web应用程序,用户需要使用他的数据库用户名和密码进行身份验证。 我想使用相同的输入用户名和密码来连接数据库。
换句话说,我想在hibernate配置文件中使用这两个字段:(dbusername和dbpassword):
<property name="hibernate.connection.username">dbusername</property>
<property name="hibernate.connection.password">dbpassword</property>
可以dynimacally填充,取决于输入用户名和密码的用户登录Web应用程序。
这可以吗?
感谢
答案 0 :(得分:8)
以下是如何实现
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml"); //hibernate config xml file name
String newUserName,newPassword;//set them as per your needs
cfg.getProperties().setProperty("hibernate.connection.password",newPassword);
cfg.getProperties().setProperty("hibernate.connection.username",newUserName);
sessionFactory = cfg.buildSessionFactory();
答案 1 :(得分:-1)
是的,你可以动态设置所有的hibernate属性, 使用
Configuration configuration = new Configuration();
configuration.configure("hibernate_sp.cfg.xml");
ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder().applySettings(configuration
.getProperties());
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());
Session session = sessionFactory.openSession();
logger.info("Test connection with the database created successfuly.");
使用配置对象设置属性。