JDNI Datasource

JDNI Datasource

https://www.baeldung.com/spring-persistence-jpa-jndi-datasource

The Java Naming and Directory Interface (JNDI) is a Java API for a directory service that allows Java software clients to discover and look up data and resources (in the form of Java objects) via a name

we're using a JNDI datasource, we won't define it in our application, we'll define it in our application container.

eg tomcat:

*<tomcat_home>/conf/server.xml, inside the element.

Postgresql

<Resource name="jdbc/BaeldungDatabase" 
auth="Container"
type="javax.sql.DataSource"
driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://localhost:5432/postgres"
username="baeldung"
password="pass1234"
maxTotal="20"
maxIdle="10"
maxWaitMillis="-1"/>


Notes; place the corresponding jar in /lib/ (in this case, PostgreSQL's JDBC jar


Also define a ResourceLink inside the element in */conf/context**.xml,* which would look like:

<ResourceLink 
name="jdbc/BaeldungDatabase"
global="jdbc/BaeldungDatabase"
type="javax.sql.DataSource"/>

use in app

@Configuration
@EnableTransactionManagement
@PropertySource("classpath:persistence-jndi.properties")
@ComponentScan("com.baeldung.hibernate.cache")
@EnableJpaRepositories(basePackages = "com.baeldung.hibernate.cache.dao")
public class PersistenceJNDIConfig {

@Autowired
private Environment env;

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
throws NamingException {
LocalContainerEntityManagerFactoryBean em
= new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());

// rest of entity manager configuration
return em;
}

@Bean
public DataSource dataSource() throws NamingException {
return (DataSource) new JndiTemplate().lookup(env.getProperty("jdbc.url"));
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}

// rest of persistence configuration
}

tomcat jndi: https://tomcat.apache.org/tomcat-8.0-doc/jndi-datasource-examples-howto.html