Application server JNDI DataSource

Application server JNDI DataSource

Java Naming and Directory Interface (JNDI) is a Java API that provides naming and directory functionality to applications. In the context of a Java EE application, JNDI is used to look up resources such as DataSource objects, which represent database connections that are managed by the application server. Integrating JNDI DataSource with Hibernate allows the application to leverage the application server’s connection pooling, transaction management, and other features, improving the efficiency and scalability of the application.

Steps to Use JNDI DataSource with Hibernate:

  1. Configure the DataSource in the Application Server : Define the DataSource in the application server’s configuration.
  2. Configure Hibernate to Use JNDI DataSource : Update Hibernate configuration to reference the JNDI.
  3. Use Hibernate in the Application : Utilize the Hibernate session to perform database operations.

JNDI DataSource

Java Example

Let’s walk through the steps to use a JNDI with Hibernate in an application.

Step 1: Configure the DataSource in the Application Server

 Example for Apache Tomcat 

Add the following configuration to the context.xml file in your Tomcat's conf directory:

xml
<Context>
    <Resource name="jdbc/MyDB" 
              auth="Container" 
              type="javax.sql.DataSource" 
              maxTotal="20" 
              maxIdle="10"
              maxWaitMillis="-1"
              username="root" 
              password="password" 
              driverClassName="com.mysql.cj.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/mydb"/>
</Context>

Step 2: Configure Hibernate to Use JNDI DataSource

Update the hibernate.cfg.xml file to reference the JNDI DataSource:

xml
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- JNDI DataSource configuration -->
        <property name="hibernate.connection.datasource">java:comp/env/jdbc/MyDB</property>
        
        <!-- Specify dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
        <!-- Other Hibernate properties -->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        
        <!-- Mappings -->
        <mapping class="com.example.MyEntity"/>
    </session-factory>
</hibernate-configuration>

Step 3: Use Hibernate in the Application
 Main.java 

java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Main {
    public static void main(String[] args) {
        // Set up the Hibernate session factory
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = null;

        try {
            session = sessionFactory.openSession();
            session.beginTransaction();

            // Create and save an entity
            MyEntity entity = new MyEntity();
            entity.setName("Test Entity");
            session.save(entity);

            // Commit the transaction
            session.getTransaction().commit();
        } catch (Exception e) {
            if (session != null) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
            sessionFactory.close();
        }
    }
}

Explanation of the Example

1.  Configure the DataSource in the Application Server :

   In the context.xml file, a DataSource named jdbc/MyDB is defined with the necessary database connection details.

2.  Configure Hibernate to Use JNDI DataSource :

   In the hibernate.cfg.xml file, the hibernate.connection.datasource property is set to java:comp/env/jdbc/MyDB, which is the JNDI name of the DataSource.

3.  Use Hibernate in the Application :

  • A Hibernate session is opened, a transaction is started, and an entity is saved to the database.
  • The transaction is committed if successful, or rolled back in case of an exception.

This example demonstrates how to configure and use a JNDI DataSource with Hibernate to leverage the application server’s resource management capabilities.

Homepage

Readmore