Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to login to Hibernate with Database Username & Password dynamically

Somewhat like how this link describes : Programmatically configure Hibernate with dynamic username and password

Only, I need the same implementation, but I am unable to specify applicationContext.xml instead of hibernate.cfg.xml, since my application specifies hibernate properties in a dataSource inside applicationContext.xml like so

<bean id="dataSourceShrms" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@192.168.100.155:1546:TSHRMS" />
    <property name="username" value="${database.username}" />
    <property name="password" value="${database.password}" />
</bean>

EDIT : Use something like JDBC login conn=DBUtils.getConnection(user, pass, host) through Java (directly from web app UI), but using Hibernate.

like image 638
FakeSheikh Avatar asked Oct 20 '22 02:10

FakeSheikh


1 Answers

Try this:

// Get the application context. Alternatively you could implement the ApplicationContextAware interface
@Autowired private ApplicationContext applicationContext;


public void setPassword(String myDynamicallyCalculatedPassword){

   BasicDataSource dataSourceShrms = applicationContext.getBean("dataSourceShrms");
  dataSourceShrms.setPassword(myDynamicallyCalculatedPassword);

}

Note: According to the documentation the set password method:

This method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked: getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.

So make sure you do not create a connection first. If you cannot do it you could try to create the connection programatically.

like image 122
borjab Avatar answered Nov 02 '22 23:11

borjab