4/16/2010

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

2 comments:

Anna said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

J2EE training

online J2EE training

Best Recommended books for Spring framework

Java Interview Questions












Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai

Vũ Diệu Linh said...

I enjoyed on reading your blog post. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. Please visit my website, Friv 4000 Games is where all the free friv games.
Friv 4000