May 5, 2020
Estimated Post Reading Time ~

CQ5 Database JNDI Connection



CQ5 can connect to an external database using its JDBC Connection pool service:

http://docs.adobe.com/docs/en/cq/5-5/developing/jdbc.html

But sometimes you could be required to access a database through a webserver JNDI connection.

There are some library that can make it easy to connect through JNDI (eg. Hibernate, Spring).

But what happen if you are not already using these libraries? Include them just to make a JNDI connection could be quite heavy and an useless overhead for your CQ instance.

The answer is quite easy, just get a reference to the DataSource using the lookup function of the InitialContext.

String jndiDb = "jdbc/mydb";
DataSource ds = null;

InitialContext ctx;
try {
ctx = new InitialContext();
ds = (DataSource) ctx.lookup(jndiDb);
log.info("ds obtained");
} catch (NamingException e1) {
log.error("Cannot get reference to datasource:" + jndiDb + ". " + e1.getMessage());
}
Of course, you can also retrieve the JNDI connection name from a bundle property, so you will not need to deploy a new bundle just to change the DB name.

It is very important you place this lookup function in the activate of your bundle, otherwise the lookup function will fail retrieving the connection to the datasource.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.