LISTING 1 LISTING 2 LISTING 3 LISTING 4
consoles, Java Management Extensions
(JMX), command-line interfaces, or
even Representational State Transfer
(REST). A datasource, however, can be
configured in a standardized way. The
@DataSourceDefinition annotation introduced with version 1. 1 of the JSR-250
specification allows the configuration,
installation, and JNDI exposure of a
datasource in a portable way, as seen in
Listing 1.
One or more @DataSourceDefinition
annotations declared on a class
(potentially enclosed with
@DataSourceDefinition annotations) and
deployed with the application provide
the necessary information for automatic installation. The datasource can
be injected directly by using the JNDI
name specified in the name element
with the @Resource annotation. It is also
accessible for a manual lookup. Direct
access to a datasource in a typical application is necessary only for accessing
stored procedure invocations or specific
optimizations and is rather uncommon. The vast majority of all persistence
use cases can be handled by JPA. The
JPA EntityManager, however, requires a
registered datasource with a well-known
JNDI name, configured in the persis-tence.xml configuration file.
The majority of Java
EE applications can be
installed without any
administrative tasks with
@DataSourceDefinition. A
properly installed JDBC
driver on the server is the
cessful installation. The obvious draw-
back here is the loss of flexibility. You
need to redeploy the application for
configuration changes.
@DataSourceDefinition(
className=" org.apache.de
rby.jdbc.ClientDataSource",
serverName="localhost",
name="java:global/jdbc/InjectionSample",
databaseName="InjectionSample;create=true",
portNumber=1527,
user="sample",
password="sample"
)
@Stateless
public class JDBCDataSourceConfiguration {
@Resource(lookup="java:global/jdbc/InjectionSample")
private DataSource dataSource;
}
COMMUNITY
JAVA IN ACTION
See all listings as text
@PersistenceContext—A Special Case
@PersistenceContext was introduced
in Java EE 5 with the JPA specification
and not as part of JSR-250. Although
an EntityManager could be consid-
ered an unshareable resource (and
EntityManagerFactory could be consid-
ered a shareable resource), it cannot be
injected with the @Resource annotation
without nasty workarounds. To inject an
EntityManager with the @Resource anno-
tation, you need to register
it in the JNDI namespace
first. The registration of
EntityManager in the JNDI
namespace can be accom-
plished by applying the
@PersistenceContext annota-
tion on the class level.
The element name binds
the EntityManager to the JNDI name.
ABOUT US
The vast majority
of all persistence
use cases can be
handled by JPA.
blog