jdbc - How to connect java application to database using JNDI? -


i implementing jndi concept connection database. googled starting point, didn't it.

the things want have simple java standalone application used jndi concept getting connected database.

sample source have is:

datasource datasource = null;  context context = null;          try {                 context = new initialcontext();          datasource = (datasource) context.lookup("database_connection");         }      catch (namingexception e) {              system.out.println("got naming exception, details -> " + e.getmessage());          } 

now, define database_connection? defined in xml file, , if specify , format of is?

if pointers can provided, great.

thanks

the real difference between question , examples you're using standalone java application. pretty-much every example assumes you're running within java ee application container. in case define database connection container, use jndi datasource, , connection that.

when jndi lookup datasource, jndi framework looks initial context factory (a class implements initialcontextfactory). in java ee application, container provides that. in standalone java application, initial context null, , no further lookups resolve correctly.

one of ways can resolve create own initial context factory:

public class mycontextfactory implements initialcontextfactory 

and inject jndi @ startup:

system.setproperty(context.initial_context_factory, "mypackag.mycontextfactory"); 

and return new objectfactory getinitialcontext call, , implement objectfactory return datasource (also custom) getconnection() call.

that work, it's overkill. easier use normal jdbc connection string approach connection directly in application rather trying use datasource. or use framework spring inject or separate database connect information code (in case you're using spring configuration files rather jndi directly).

the 1 reason i'd advocate creating custom context factory , data source approach if have common jpa code want run both within java ee app , within standalone app (it's otherwise non-trivial configure same code both). doesn't sound case.

so, since you're standalone , not in java ee container, think real answer use case not appropriate datasource (unless move framework spring provide one).


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -