Getting a Database Connection Using JNDI

I've looked this up enough times, so I thought I'd jott this down. This is how I look up my JNDI resource from Java:

private final mJNDIResourceName = "my_data_source";
[..]
InitialContext context = new InitialContext();
Context envContext = (Context) context.lookup("java:comp/env");
DataSource dataSource = (DataSource) envContext.lookup(mJNDIResourceName);
connection = dataSource.getConnection();
connection.setAutoCommit(false);

Most examples on the internet use ajdbc/ prefix, likejdbc/my_data_source. This is just some kind of convention, you don'd need to havejdbc/ in the name. I've removed it from my code because I find it totally redundant and without any added value.

I've previously described how you configure DB pooling in Tomcat, which also is a JNDI resource. Hence, if you're using Tomcat, you can use this article as a reference for setting it up.

Good luck.


~ /home 🏠 ~ talks 💬 ~ bash ~ craftsmanship ~ db ~ dongxi ~ emacs ~ escenic ~ iam ~ java ~ js ~ language ~ latex ~ ldap ~ life ~ linux ~ llm ~ mac-os-x ~ mt-foo ~ network ~ norsk ~ python ~ quotes ~ running ~ security ~ travel ~ unix ~ various ~ vcs ~ webdesign ~ windows ~ discoveries ~ cv 🧙 ~

Licensed under CC BY Creative Commons License ~ 📡 RSS feed ~ ✉ torstein.k.johansen @ gmail ~ 🐘 @skybert@hachyderm.io ~ 🎥 youtube.com/@skybert