
Using @DataSourceDefinition in Java EE 6 With Postgresql
Introduction
Java EE applications use DataSource
objects when they access relational databases through the JDBC API. Typically the Datasource
that should be used is referenced by its Java Naming and Directory Interface (JNDI) name in the persistence.xml
file:
> java:app/env/myDatasource>
The Datasource
details (host, username, password, database type) for this JNDI name need to be declared somewhere. Prior to Java EE 6, you could create a DataSource object using vendor-specific mechanisms. This could be a deployment descriptor for the application server in the WAR, e.g. glassfish-web.xml
or XML configuration files in the application server directory.
In Java EE 6 the @DataSourceDefinition annotation was introduced. With this annotation you can declare ‘application server agnostic’ datasources directly in your code. While this is usually a bad idea for production code, it can be very useful for testing, since you don’t have to change the configuration of the application server. You can just deploy the WAR in any application server and it will run.
In this example we run through the steps for…