How to set up JNDI DataSource with PostgreSQL? - java
I am learning Java EE. My instructor told me to implement JNDI DataSource in my learning project. I have found some articles on the subject but I can't see clearly the steps to doing this.
My training project is a Spring MVC application. On the front end it has some Thymeleaf templates, and the data are taken from a PostgreSQL database.
What should be done to implement JNDI here? I don't even know why I need it. I was only told that this configuration should be considered obsolete and low-level, but I have no idea why.
Now the database is configured as follows:
a props file with the following content:
driver=org.postgresql.Driver
url=jdbc:postgresql://localhost/trainingproject
dbuser=postgres
dbpassword=Password
a .sql file which looks like this:
DROP TABLE IF EXISTS table1;
CREATE TABLE table1
(
row1 SERIAL PRIMARY KEY,
row2 CHARACTER VARYING(64)
);
a DataSource bean:
#Bean
public DataSource datasource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getProperty(DRIVER));
dataSource.setUrl(environment.getProperty(URL));
dataSource.setUsername(environment.getProperty(USER));
dataSource.setPassword(environment.getProperty(PASSWORD));
}
PGSimpleDataSource implementation of DataSource is bundled with JDBC driver.
The JDBC driver for Postgres at https://jdbc.postgresql.org includes an implementation of DataSource: PGSimpleDataSource
PGSimpleDataSource ds = new PGSimpleDataSource() ;
ds.setServerName( "localhost" );
ds.setDatabaseName( "your_db_name_here" );
ds.setUser( "scott" );
ds.setPassword( "tiger" );
For more info:
The Javadoc for DataSource.
The Javadoc PGSimpleDataSource.
My Answer to the Question, Produce a DataSource object for Postgres JDBC, programmatically
The JDBC driver’s manual.
JNDI
Your question conflates two issues: DataSource and JNDI.
A DataSource is a simple object holding all the connection info needed to make a connection to a database. This includes a username, a password, the address of the database server, and any number of standard and proprietary feature settings. By proprietary, I mean Postgres-specific feature settings versus Microsoft SQL Server-specific versus Oracle-specific, etc. Look at the Javadoc for DataSource to see how simple it is, basically just a getConnection method. You can obtain a DataSource object with or without JNDI; the two are orthogonal issues.
JNDI is much more complex. JNDI is an interface for obtaining from a naming/directory server the configuration info needed by your app at runtime. Using this interface to such a server means you need not include deployment details in your codebase; you look up needed details on-the-fly at runtime.
Database connection info is but one of many kinds of info you might want to obtain from a JNDI server. You might also look up web services servers, logging services, and so on.
So rather than hard-coding your database connection info, you might want to “discover” the proper database connection info when launching your app. Your testing machines will use a bogus database server while your production deployment machines will use a different database server. These database servers may not be known to the programmer at compile time, or may not even exist yet. A look-up needs to be done, and JNDI is a standard way to do so without vendor lock-in.
How you configure database connection info to be delivered by a JNDI-compliant naming/directory server as a DataSource object to your app differs wildly depending on the particular server environment of your enterprise. Given your last code example, it looks like you are not actually accessing a JNDI server in your class, so JNDI is moot.
Related
Dynamically datasource with hibernate and netbeans
How I can create web application project which is loading the jndi datasource set in the server configuration? I want to make the web application independent from the server and the database. Is it possible.
You create the DataSource in your web/application server and expose it through JNDI You configure the following hibernate property: <property name="hibernate.connection.datasource">java:comp/env/jdbc/MyDataSource</p> This way the application is decoupled from the JNDI provider. Even the JNDI url can be configured using a Maven property, so switching to an application server (that uses a different JNDI resource pattern) is just a mater of adding a new Maven profile. One better approach is to set up the DataSource in your application configuration. #Autowired private DataSource dataSource; ... properties.put("hibernate.connection.datasource", dataSource); This way you can use any connection pooling framework, like the fastest connection pooling framework, HikariCP. You can even set up DataSource proxies, like: datasource-proxy, to log SQL queries with PreparedStatement parameters FlexyPool, to monitor connection pooling usage and adjust the pool size using adapting startegies
Create Datasource in Code or get it via JNDI from Application Server
In a java application, If we want to use javax.sql.DataSource instead of java.sql.DriverManager to get connections, which approach would be better to create DataSource and WHY? Create DataSource in the application itself at the application startup time or Configure DataSource in the application server and get it via JNDI
Well, it actually depends upon the requirement. You can take this as a general rule.If you have multiple applications and sharing the same DataSource, then it can be a good choice to configure the DataSource in the server. Otherwise, if this is the only application uses the DataSource, then you can have it in the application level itself.
What is faster: JDBC or JNDI?
I have two options to configure my application database connection - one is using JDBC, another one is using JNDI. What will be the best option in terms of how fast those connection types work with the database. I understand those are two different types of database connections using different principles (JDBC is a direct db connection, JNDI is a database connection pool configuration on application server side). But are there other general JDBC/JNDI pros and cons which might be more important than operating speed? If yes, what are they?
A database connection always uses JDBC. With JNDI you register a datasource in a directory service which can be looked up by its name. Thus JDBC and JNDI are completly different and not interchangeable.
I bet what you mean is choosing from creating datasource or jdbc connection manually in your application, or setup the datasource in the container, and application lookup the datasource through JNDI If it is the case, always stick to 2 if possible. The main reasons for the choice is never the performance differences. The reason for sticking to 2 is in most cases is, you need 2 to gain more advanced features from container, for example, distributed transaction.
This is what i have found about JNDI and JDBC. JNDI: This is a technology which works like a telephone directory which is used to search the name on server and datasource remotely. JNDI creates a connection pool. Connection pool is an environment on the server where JNDI and Database encapsulated to for Type4 connectivity. JDBC: A Java API that enables Java programs to execute SQL statements. This allows Java programs to interact with any SQL-compliant database. JDBC is similar to ODBC, but is designed specifically for Java programs, whereas ODBC is language-independent. JDBC was developed by Sun Microsystems. JNDI is faster and efficient.
Not totally clear on the question. JNDI isn't a type of database connection. You can use JNDI to look up a DataSource, which is a factory for connections. The DataSource is part of the JDBC API though, so JNDI works with JDBC as opposed to being alternatives here. Are you talking about using JDBC against a database for directory information, vs. using JNDI against an LDAP repo?
The real speed benefit comes from being able to reuse database connections. Hence, you need to use an approach which provides database connection pooling, and then use the appropriate technology to get to the pool. Depending on implementation this can be either JDBC (if the driver supports it itself) or JNDI or something completely different. If your application runs inside a web container, it is common to use JNDI to allow the pool to be configured and managed in the web container instead of inside your application.
As mentioned in previous answers, using Datasource is the same as using JDBC in terms of technology. Nevertheless, using a Datasource is usually the preffered way because that way you have the server managing your DB connection pools.
Whether connection pooling is used does not affect application code. It does not require any code changes to the application because the application performs a lookup on a JNDI name of a previously registered data source. If the data source specifies a connection pooling implementation during JNDI registration (as described in section Creating a Data Source Using the DataDirect Connection Pool Manager), the client application benefits from faster connections through connection pooling.
The question is meaningless. Faster at what? There is nothing to compare. JDBC is a general-purpose interface to relational databases. JNDI is a general-purpose interface to naming systems. The strong probability is that the efficiency of either depends 99% on the target system being communicated with. In any case relational databases and naming systems fulfil completely different needs that are largely non-comparable. Usually JNDI is used to obtain a connection, then JDBC is used to operate with that connection.
How do I use JDBC's data source?
I've tried researching how to use the DataSource method of connecting to a database but never could find out how. I know that a DataSource is first configured and registered to JNDI in an application that is separate from the user application, and all the user application will do is retrieve it using JNDI. What I don't understand is where the DataSource is configured. Is it automatically registered when I turn on MySQL, do I need to download another application to register it, or do I make a new class that will do that for me?
You usually have a Java EE app server like Glassfish, WebLogic, JBOSS, Tomcat, or Jetty have a JNDI provider that you should be using for the lookup. Here's how you do it with Oracle. Here's how you do it with MySQL. The JDK 6 javadocs say that a basic DataSource can supply a connection if your driver has such an implementation. I would recommend looking at the Connector-J docs to see if you can do it without JNDI lookup services.
Datasource creation in JBOSS for DB2
How JBOSS uses db2-ds.xml file to create datasource object for DB2?
If it is about how to create a DataSource you copy $JBOSS_HOME\docs\examples\jca\db2-ds.xml to $JBOSS_HOME\server\default\deploy and customize the settings to fit your JDBC connection-url,user-name etc. EDIT: Jboss reads this file, and periodically checks for updates (if configured) and sets up a DataSource which is registered in JNDI and provides a pool of connections depending on underlying driver-class. To see how this is done in detail you should throw a glance into the sourcecode. Search for "-ds.xml" a good startingpoint is: $JBOSS_SRC\console\src\main\org\jboss\console\manager\DeploymentFileRepository.java which looks for "-ds.xml" files.