DataSourceDefinition Examples in JavaEE 6

The usual way to create a DataSource is through the appserver's administration, CLI or GUI tool. Then applications can declare resource-ref mapped to the DataSource. This involves both application developer and server administrator, and sometimes can be too much for simple apps. JavaEE 6 added 2 annotations to ease this task: javax.annotation.sql.DataSourceDefinition and javax.annotation.sql.DataSourceDefinitions.

With the 2 annotations, applications can take control of DataSource creation, and choose to expose the DataSource in various scopes: component-, module-, application, and global-scope. For simple apps, all this can be done without any server configuration or XML descriptors.

Example 1: a servlet declares how to create a derby DataSource, and injects a reference to this DataSource into a field. This DataSource is scoped to the whole module (the entire webapp).
@DataSourceDefinition(name="java:module/env/inventory",
className="org.apache.derby.jdbc.ClientDataSource",
portNumber=1527,
serverName="localhost",
databaseName="inventory",
user="user1",
password="password1")
@WebServlet(urlPatterns = "/InventoryServlet")
public class InventoryServlet extends HttpServlet {
@Resource(lookup="java:module/env/inventory")
private DataSource inventoryds;
Example 2: a Stateless session bean creates an application-scope Oracle DataSource, and injects its resource-ref. This DataSource is visible to the entire application (EAR).
@DataSourceDefinition(name="java:app/env/inventory",
className="oracle.jdbc.pool.OracleDataSource",
portNumber=1521,
serverName="localhost",
databaseName="inventory",
user="user1",
password="password1",
properties={"driverType=thin"}
)
@Stateless
public class InventoryBean {
@Resource(lookup="java:app/env/inventory")
private DataSource inventoryds;
For more details, see JavaEE 6 javadoc page for @DataSourceDefinition

Followers

Pageviews Last 7 Days