Tuesday Jan 22, 2013

Default DataSource in Java EE 7: Lesser XML and More Defaults (TOTD #196)


Section E.5.5.20 in the Java EE 7 Platform specification defines a new Default Data Source that must be provided by a Java EE 7-compliant runtime. This pre-configured data source can be used by application for accessing the associated database. It is accessible to the application under the JNDI name:
java:comp/DefaultDataSource

This can be accessed in the application as:
@Resource(name="myDataSource", lookup="java:comp/DefaultDataSource")
DataSource myDS;

If the binding is not specified, the mapping of the reference will default to this default data source. So the above fragment is equivalent to:
@Resource(name="myDataSource")
DataSource myDS;

Section 8.2.1.5 in the JPA 2.1 specification says

If neither jta-data-source and non-jta-data-source elements are specified, the deployer must specify a JTA data source at deployment or a JTA data source must be provided by the container, and a JTA EntityManagerFactory will be created to correspond to it.

Per.book
This means a Java EE 7 application can have the following persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="myPU" transaction-type="JTA">
<jta-data-source>java:comp/DefaultDataSource</jta-data-source>
</persistence-unit>
</persistence>

This is semantically equivalent to:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="movieplex7PU" transaction-type="JTA"/>
</persistence>

Notice, no jta-data-source.

In both cases, the default data source will be provisioned and available to the application. In GlassFish 4, this is bound to the JDBC resource jdbc/__default.

And this can be verified by giving the command:
./bin/asadmin list-jdbc-resources
jdbc/sample
jdbc/__TimerPool
jdbc/__default
Command list-jdbc-resources executed successfully.

Lesser XML and more defaults makes Java EE 7 more lightweight and user friendly!

Download GlassFish 4.0 promoted build and try it today!

About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« January 2013 »
SunMonTueWedThuFriSat
  
1
3
4
5
6
8
9
10
12
13
14
15
16
17
19
20
21
23
24
25
27
31
  
       
Today