loading...empty;done;/connection-to-db-via-jndi/:-uriDatabase Connection via JNDI | iNET.elastic Dev Docs

Connection to DB using JNDI

To connect to DB using JNDI you have to perform the following steps:

  • Log onto PaaS dashboard
  • Create an environment
  • Add database node into your environment
  • Modify some configuration files in a web-app
  • Create a connection in a java-class

Let’s do it step-by-step:

1. Create environment with database (MySQL in our case):

connection to db via jndi env

2. Create a new user in a database:
How to create new user - click here

1
2
3
Database name : iNET.elasticDb
User_name : iNET.elastic
Password : iNET.elastic

3. Modify configuration files in your web-application:
context.xml:

1
2
3
4
5
6
<Context antiJARLocking="true" path="/JNDI">
    <Resource name="jdbc/iNET.elasticDb" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="iNET.elastic" password="iNET.elastic" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://mysql-jndi-example.{hoster_domain}/iNET.elasticDb"/>
</Context>

web.xml:

1
2
3
4
5
6
<resource-ref>
 <description>MySQL Datasource example</description>
 <res-ref-name>jdbc/iNET.elasticDb</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
</resource-ref>

4. Create connection in java-class

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class MyConnection {

    private DataSource dataSource;

    public MyConnection() {
        try {

            InitialContext context = new InitialContext();
            dataSource = (DataSource) context.lookup("java:comp/env/jdbc/iNET.elasticDb");

        } catch (NamingException ex) {
            Logger.getLogger(MyConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Connection getConnection() {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException ex) {
            Logger.getLogger(MyConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return conn;
    }
}

What’s next?