user2549122
user2549122

Reputation: 203

how to used data source declared in tomee.xml in java class

Hi i configure data source in tomee.xml file and web.xml file.this will work fine when i executing my project but i implmented test case where also i need to used when i used there then its will giving exception javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial

This is my tomee.xml file

     <?xml version="1.0" encoding="UTF-8"?>
     <tomee>
       <Resource id="jdbc/mydb" type="DataSource">
             JdbcDriver com.mysql.jdbc.Driver    
             JdbcUrl jdbc:mysql://localhost:3306/test
             UserName root
             Password root    
             JtaManaged false   
             InitialSize 50 
             MaxActive 100
             MaxIdle 3
       </Resource>
     </tomee>

This code is working fine in Servlet but when i am writing in java class then its giving exception this is my java class for accessing

     Context initContext = new InitialContext();
     Context envContext  = (Context)initContext.lookup("java:/comp/env");
     DataSource ds = (DataSource)envContext.lookup("jdbc/mydb");
     con = ds.getConnection();

Upvotes: 0

Views: 2299

Answers (1)

Kayaman
Kayaman

Reputation: 73578

In a Servlet environment you have a context already set up by the servlet engine. When you run outside of such an environment, you need to set up the context yourself.

See an example here.

Upvotes: 1

Related Questions