5

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.

2
  • Please elaborate the dynamic part. Commented Sep 14, 2015 at 9:34
  • Meaning, after the application has been run and deployed, basically from the web application UI. Commented Sep 14, 2015 at 9:39

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but I am stuck here : 1 ) Reading applicationcontext.xml from /<ProjectName>/WebContent/WEB-INF/applicationContext.xml. As of now I am placing the file in the .properties package and reading it like so - applicationContext = new ClassPathXmlApplicationContext("/com/org/proj/messages/applicationContext.xml"); 2) After setting dynamic username and password, How do I connect and ensure those values to be used throughout ?
1

Imagine that you have your database url, driverClassname, username and password in variables with the same name. On your case those variables would be filled from the input page or wherever the user itroduces that data.

And you have a class MyClass class configured with Hibernate annotations on the package com.myapplication.POJO

So, you just create Configuration object and query the database:

Configuration configuration = new Configuration().configure() .setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle8iDialect") .setProperty("hibernate.connection.driver_class", driverClassname) .setProperty("hibernate.connection.url", url) .setProperty("hibernate.connection.username", username) .setProperty("hibernate.connection.password", password) //In next line you just tell Hibernate which classes are you going to query configuration = configuration.addPackage("com.myapplication.POJO"). addAnnotatedClass(MyCustomClass.class); StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()); SessionFactory factory = configuration.buildSessionFactory(ssrb.build()); //We open session with database Session session = factory.openSession(); List<MyCustomClass> result = null; try { //Here we get the list of MyCustomClass objects from database result = session.createQuery("FROM MyCustomClass").list(); } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } 

IMPORTANT: I think Oracle8iDialect is the most common for Oracle DB. If you are using Oracle 10g or Oracle 9i you should use org.hibernate.dialect.Oracle10gDialect or org.hibernate.dialect.Oracle9iDialect. Complete reference here: http://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/dialect/package-summary.html

7 Comments

Didnt get 'create configuration' part. Will this configure applicationContext.xml file ?
Whit this Configuration object, I just do the following: StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); factory = configuration.buildSessionFactory(ssrb.build()); Session session = factory.openSession(); Then you can use the session Object to query the database.
I am using applicationContext.xml. So this will not work. Please suggest a workaround that is pertinent for applicationContext.xml
I've just changed the solution to fit your specific requiriments. Please check if it works.
Thank you @JavierFromMadrid, but from what I can understand, this reads url, username, password from basicDataSource, like in basicDataSource.getUsername() etc. which is from applicationContext.xml, which has the values specified. I need to dynamically specify them. In my existing implementation, I have specified username, password, url,hostname as static values in my dataSource. I need to avoid this and enable the user to enter these values and connect to the database from the application. Like JDBC has in conn=DBUtils.getConnection(user, pass, host);, but using Hibernate.
|
0

You can define the Hibernate property as below,

Refer: http://www.mkyong.com/spring/maven-spring-hibernate-mysql-example/

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource"/> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> 

Comments

0

You can use dynamic values in your applicationContext.xml. For example you can read values from a external properties file pointed by a Environmental variable that conaints a path to a file:

<context:property-placeholder location="file:${my_environmental_variable_name}/project.properties" /> 

Asuming that your properties file contains:

hibernate.connection.url=jdbc:mysql://localhost:3306/yourapplication hibernate.connection.username=username hibernate.connection.password=yourpassword 

You can use them in yout applicationcontext.xml this way:

<bean id="dataSourceShrms" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="oracle.jdbc.OracleDriver" /> <property name="url" value="${hibernate.connection.url}" /> <property name="username" value="${hibernate.connection.username}" /> <property name="password" value="${hibernate.connection.password}" /> </bean> 

So you can run your application defining each time a different value for your 'my_environmental_variable_name' environmental variable pointing to different properties configuration file.

4 Comments

This is the direction is was trying in, but for this i'd have to modify the (for eg.) database.properties file located in a package. I was doubtful of whether this was a correct approach or not. Anyway ran into certain issues when updating that file.
Maybe the environmental property can contain the configuration properties filename inside your package. Try changing to this <context:property-placeholder location="file:${my_environmental_variable_properties_filename}" /> Feel free to upvote if you consider this answer good enough.
Yes, thanks, I am aware of this and I have already done so, but I faced issues while modifying the properties file, which I feel is not the right practice. Please refer to my comment above. If you are suggesting modifying the properties file at runtime then pls suggest something in that direction.
No, i was not talking about modifying the properties file. I was suggesting to use various properties files. i.e.: config1.properties, config2.properties, etc. So when you run your program you can specify wich file to use with the environment variable. i.e.: 'java myClass.class -Dmy_environmental_variable_name=config2.properties'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.