Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

Difference between revisions of "EclipseLink/Examples/MySports"

m (Configure Eclipse Environment)
(Persistence)
 
(11 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 
<div style="float:right;width:300px"><div style="background:#ffffff;width:275px" align="center">[[Image:EclipseLink_Mysports.png]]__TOC__</div></div>
 
<div style="float:right;width:300px"><div style="background:#ffffff;width:275px" align="center">[[Image:EclipseLink_Mysports.png]]__TOC__</div></div>
  
= EclipseLink MySports Example =
+
In this example users can view and modify information for multiple sports leagues including extended attributes with the additional mapping information stored in an external source.
 +
 
 +
The MySports example is a web application which demonstrates EclipseLink's latest features:
 +
* '''Multi-tenancy''' (Tenant isolation): The application can be deployed as a SaaS solution with multiple leagues being hosted by a common application instance and a shared database with the choice of:
 +
** @Multitenant(SINGLE_TABLE) - row level isolation using LEAGUE_ID column values
 +
** @Multitenant(TABLE_PER_TENANT) - separate tables using league id as table name suffix
 +
* '''Extensibility''': Each League's divisions, teams, and players can be extended dynamically to store and support querying of additional administrator defined properties.
 +
* External Metadata: Using the JPA and JAXB MetadataSource capabilities the tenant specific extensions and mapping definitions are stored in the MySports Admin application enabling dynamic league provisioning and customization.
 +
* '''EMF per Tenant''': Extends EclipseLink to construct a separate EMF for each hosted league.
 +
* '''JPA-RS''': Excposes both the MySposrts and MySports Admin apps using REST
  
The MySports example is a web application which demonstrates EclipseLink's latest features related to multi-tenancy. In this example users can view information for various leagues (tenants) including extended attributes with the additional mapping information stored in an external source.
 
  
 
== Example Overview ==
 
== Example Overview ==
Line 17: Line 25:
 
In order to setup and run this example the following install and configure steps must be followed carefully.
 
In order to setup and run this example the following install and configure steps must be followed carefully.
  
 +
The MySports application is developed within its own . Using any GIT tools the example can be checked out anonymously.
  
 
=== Prequisites ===
 
=== Prequisites ===
 
To run the MySports example, you will need the following:
 
To run the MySports example, you will need the following:
# GlassFish 3.1 (http://glassfishplugins.java.net/eclipse36/)  
+
# GlassFish 3.1.2  (http://glassfishplugins.java.net/eclipse36/)  
# Eclipse Java EE with GlassFish adapter (http://www.eclipse.org/downloads/)
+
# Eclipse Java EE IDE with GlassFish adapter (http://www.eclipse.org/downloads/)
# EclipseLink 2.3.1 OSGi Bundles (http://www.eclipse.org/eclipselink/downloads/)
+
#* Example has projects setup for Eclipse usage but code should be usable in any development environment.
 +
# EclipseLink 2.4 Bundles ([http://www.eclipse.org/eclipselink/releases/2.4.php])
  
=== Upgrade and Configure GlassFish===
+
=== Basic Steps ===
Use this procedure to upgrade GlassFish to use the current EclipseLink version and prepare the connection pool.
+
#Replace the following JAR files from '''<GLASSFISH_HOME>\glassfish\modules\''' with the JAR files from the EclipseLink OSGI bundle:
+
#*org.eclipse.persistence.antlr.jar
+
#*org.eclipse.persistence.asm.jar
+
#*org.eclipse.persistence.core.jar
+
#*org.eclipse.persistence.jpa.jar
+
#*org.eclipse.persistence.jpa.modelgen.jar
+
#*org.eclipse.persistence.oracle.jar
+
#Copy the following JAR file from the EclipseLink OSGI bundle to  '''<GLASSFISH_HOME>\glassfish\modules\''':
+
#*org.eclipse.persistence.moxy_2.3.0.v20110604-r9504.jar
+
#Use the GlassFish Admin Console to create a new JDBC resource named '''jdbc/MySports''' and a new JDBC connection pool named '''MySportsPool'''. In this example, we will use the embedded Derby database:
+
#* Resource type: javax.sql.DataSource
+
#* Datasource classname: org.apache.derby.jdbc.EmbeddedDataSource40 <br />'''Note''': Be sure to edit the JDBC Connection Pool properties to reflect your database connection information. In this example, we will use:
+
#* User: APP
+
#* Password: APP
+
#* ServerName: localhost
+
#* DatabaseName: gemini
+
#* PortNumber: 1527
+
[[Image:Mysports jdbc.png]]
+
  
===Configure Eclipse Environment ===
+
# Clone the [http://git.eclipse.org/c/eclipselink/examples/mysports.git/ MySports GIT repositiory]
Now you can configure Eclipse to run the MySports example.
+
# Upgrade GlassFish to use EclipseLink 2.4 [[EclipseLink/Examples/MySports/GlassFish]]
#Add a variable named '''eclipselink_2.3_jar''' with the value '''<ECLIPSELINK OSGI BUNDLE>\org.eclipse.persistence.core_2.3.0.<BUILD>.jar'''. <br />This is used for the javaagent of the test project. You can add this variable by creating a String Substitution variable, as shown here: <br />[[Image:Mysports variable.png]]
+
## Ensure GlassFish server is configured
#Obtain the three example projects from the EclipseLink SVN repository: <br />'''Note''': If you use the Eclipse Team Provider for SVN plugin (http://www.eclipse.org/subversive/downloads.php) Eclipse will can import the example projects.
+
## Configure a jdbc/MySports JDBC resource and supporting connection pool to a MySQL database
#*http://dev.eclipse.org/svnroot/rt/org.eclipse.persistence/branches/2.3/trunk/examples/my-sports/MySports/
+
# Open the MySports projects in Eclipse
#*http://dev.eclipse.org/svnroot/rt/org.eclipse.persistence/branches/2.3/trunk/examples/my-sports/MySportsAdmin/
+
## Configure Eclipse - [[EclipseLink/Examples/MySports/Eclipse]]
#*http://dev.eclipse.org/svnroot/rt/org.eclipse.persistence/branches/2.3/trunk/examples/my-sports/MySportsTests/ <br />[[Image:Mysports svn.png]]
+
## Fix any project library dependencies on GlassFish and target server
#Start the Derby server. The GlassFish installation includes a Derby instance that can be used, in the '''<GLASSFISH_HOME>\javadb\''' folder.
+
# Customize MySports Tests/eclipselink-example-mysports.properties to point to the same MySQL database as connection pool in GlassFish
#Import the EclipseLink MySports projects into Eclipse.
+
# Run MySports AllTests run target. This will setup the table and populate the initial leagues
#Create a new Derby connection profile. Use the same JDBC Connection Properties that you used when creating the GlassFish connection pool.
+
#Add the Connectivity Driver Definition for the Derby database to the project. <br />[[Image:Mysports derbyclientjar.png]]
+
#Edit the '''eclipselink-examples-mysports.properties''' file to match your database connection information. <br />[[Image:Mysports properties.png]]
+
 
+
==Running the Example==
+
Now, you're ready to run the MySports example.
+
#Run the '''MySports AllTests''' launch target. This will create the database tables and prepare an initial population
+
#Run the '''MySports Admin''' application
+
#Run the '''MySports''' application
+
  
 
== Example Details ==
 
== Example Details ==
Line 124: Line 106:
 
The persistence layer is the main purpose of this example application. The persistence layer makes use of application bootstrapped persistence contexts with support for an EntityManagerFactory and backing ServerSession (with Cache) per league (tenant). This all bootstrapped off of a single persistence-unit definition.
 
The persistence layer is the main purpose of this example application. The persistence layer makes use of application bootstrapped persistence contexts with support for an EntityManagerFactory and backing ServerSession (with Cache) per league (tenant). This all bootstrapped off of a single persistence-unit definition.
  
==== Runtime Architecture ====
 
 
<div align="center">
 
[[Image:Mysports_persistence.png]]
 
</div>
 
  
 
==== LeagueRepository ====
 
==== LeagueRepository ====
Line 191: Line 168:
 
=====EMF per Tenant =====
 
=====EMF per Tenant =====
  
When developing an application that can handle requests from multiple tenants you can choose to have a single EntityManager Factory (EMF) with tenant scoped EntityManagers (EM) or you can choose to have a EMF per tenant. The decision really comes down to the number of tenants and the value of maintaining a cache that can be shared upon user requests for the same tenant. In this example application where there are a limited number of tenants the decision was made to use an EMF per tenant.
+
When developing an application that can handle requests from multiple tenants you can choose to have a single EntityManager Factory (EMF) with tenant scoped EntityManagers (EM) or you can choose to have a EMF per tenant. The decision really comes down to the number of tenants and the value of maintaining a cache that can be shared upon user requests for the same tenant and any usage of extended attributes per tenant. In this example application where there extensions per tenant and a limited number of tenants the decision was made to use an EMF per tenant.  
 
+
EMF per tenant leverages a shared persistence unit definition (persistence.xml):
+
 
+
<source lang="xml">
+
<persistence-unit name="mysports" transaction-type="RESOURCE_LOCAL">
+
<non-jta-data-source>jdbc/MySports</non-jta-data-source>
+
+
<class>example.mysports.model.User</class>
+
<class>example.mysports.model.Team</class>
+
<class>example.mysports.model.Player</class>
+
<class>example.mysports.model.Division</class>
+
 
+
<validation-mode>NONE</validation-mode>
+
</source>
+
 
+
This definition is then used with separate shared EclipseLink sessions and caches being created per tenant using persistence unit properties passed into the call to create the EMF:
+
 
+
'''LeagueRepository.createEMF''':
+
<source lang="java">
+
emfProps.put(SESSION_NAME, getConfig().getSessionName(leagueId));
+
emfProps.put(LEAGUE_CONTEXT, leagueId);
+
emfProps.put(MySportsConfig.class.getName(), getConfig());
+
 
+
this.emf = Persistence.createEntityManagerFactory(PU_NAME, emfProps);
+
</source>
+
 
+
The SESSION_NAME property is what uniquely identifies the shared session and cache used for the EMF. If multiple create requests are issues with the same value on the same class-loader they will each be given new EMF instances but will share the same shared session and cache. The LEAGUE_CONTEXT property is the value that is set on the EMF to identify the tenant required by @Multitenant on the entities. The third EMF property is simply a way to cache the MYSportsConfigf instance within the shared session.
+
  
==== MOXy (JAXB) Usage ====
+
[[EclipseLink/Examples/MySports/EMFperTenant | Lear more...]]
  
The MySports application uses of EclipseLink MOXy to map its persistent entities into XML within the JAX-RS (RESTful) interface. The mapping is done using an '''eclipselink-oxm.xml''' mapping file instead of JAXB annotations.
+
==== JPA-RS ====
  
<pre>
+
The REST interface for MySports is provided by EclipseLink JPA-RS.
<?xml version="1.0"?>
+
<xml-bindings version="2.3"
+
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
+
package-name="example.mysports.model" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
xsi:schemaLocation="http://www.eclipse.org/eclipselink/xsds/persistence/oxm http://www.eclipse.org/eclipselink/xsds/eclipselink_oxm_2_3.xsd">
+
<java-types>
+
<java-type name="Divisions" xml-accessor-type="FIELD">
+
<java-attributes>
+
<xml-element java-attribute="divisions" xml-path="divisions" />
+
</java-attributes>
+
</java-type>
+
<java-type name="Division" xml-accessor-type="FIELD">
+
<xml-root-element />
+
<xml-virtual-access-methods />
+
<java-attributes>
+
<xml-attribute java-attribute="id" />
+
<xml-attribute java-attribute="version" />
+
<xml-attribute java-attribute="name" />
+
<xml-element java-attribute="teams" xml-path="teams/team" />
+
<xml-transient java-attribute="attributes" />
+
<xml-transient java-attribute="defaultDivision" />
+
</java-attributes>
+
</java-type>
+
<java-type name="Team" xml-accessor-type="FIELD">
+
<xml-root-element />
+
<xml-virtual-access-methods />
+
<java-attributes>
+
<xml-attribute java-attribute="id" />
+
<xml-attribute java-attribute="version" />
+
<xml-element java-attribute="name" />
+
<xml-element java-attribute="players" xml-path="players/player" />
+
<xml-inverse-reference java-attribute="division"
+
mapped-by="teams" />
+
<xml-transient java-attribute="attributes" />
+
</java-attributes>
+
</java-type>
+
<java-type name="Player" xml-accessor-type="FIELD">
+
<xml-root-element />
+
<xml-virtual-access-methods />
+
<java-attributes>
+
<xml-attribute java-attribute="id" />
+
<xml-attribute java-attribute="version" />
+
<xml-attribute java-attribute="userid" />
+
<xml-element java-attribute="firstName" xml-path="name/@first" />
+
<xml-element java-attribute="lastName" xml-path="name/@last" />
+
<xml-inverse-reference java-attribute="team"
+
mapped-by="players" />
+
<xml-transient java-attribute="attributes" />
+
</java-attributes>
+
</java-type>
+
</java-types>
+
</xml-bindings>
+
</pre>
+

Latest revision as of 13:54, 21 June 2012

In this example users can view and modify information for multiple sports leagues including extended attributes with the additional mapping information stored in an external source.

The MySports example is a web application which demonstrates EclipseLink's latest features:

  • Multi-tenancy (Tenant isolation): The application can be deployed as a SaaS solution with multiple leagues being hosted by a common application instance and a shared database with the choice of:
    • @Multitenant(SINGLE_TABLE) - row level isolation using LEAGUE_ID column values
    • @Multitenant(TABLE_PER_TENANT) - separate tables using league id as table name suffix
  • Extensibility: Each League's divisions, teams, and players can be extended dynamically to store and support querying of additional administrator defined properties.
  • External Metadata: Using the JPA and JAXB MetadataSource capabilities the tenant specific extensions and mapping definitions are stored in the MySports Admin application enabling dynamic league provisioning and customization.
  • EMF per Tenant: Extends EclipseLink to construct a separate EMF for each hosted league.
  • JPA-RS: Excposes both the MySposrts and MySports Admin apps using REST


Example Overview

The MySports example includes the following projects: MySports: A dynamic web project which deploys the primary application, exposing a JSF and JAX-RS (REST) front-end.

MySports Admin: Administration console for the project.

MySports Tests: A Java project containing Junit tests that verifies the functionality of the example and creates the necessary database tables

Installation and Configuration

In order to setup and run this example the following install and configure steps must be followed carefully.

The MySports application is developed within its own . Using any GIT tools the example can be checked out anonymously.

Prequisites

To run the MySports example, you will need the following:

  1. GlassFish 3.1.2 (http://glassfishplugins.java.net/eclipse36/)
  2. Eclipse Java EE IDE with GlassFish adapter (http://www.eclipse.org/downloads/)
    • Example has projects setup for Eclipse usage but code should be usable in any development environment.
  3. EclipseLink 2.4 Bundles ([1])

Basic Steps

  1. Clone the MySports GIT repositiory
  2. Upgrade GlassFish to use EclipseLink 2.4 EclipseLink/Examples/MySports/GlassFish
    1. Ensure GlassFish server is configured
    2. Configure a jdbc/MySports JDBC resource and supporting connection pool to a MySQL database
  3. Open the MySports projects in Eclipse
    1. Configure Eclipse - EclipseLink/Examples/MySports/Eclipse
    2. Fix any project library dependencies on GlassFish and target server
  4. Customize MySports Tests/eclipselink-example-mysports.properties to point to the same MySQL database as connection pool in GlassFish
  5. Run MySports AllTests run target. This will setup the table and populate the initial leagues

Example Details

MySports Domain (example.mysports.model)

The domain model is that of any arbitrary sports league. The intent is to build an application that captures the state of an arbitrary league and use it in a multitenant application where multiple leagues (tenants) can be hosted. The domain model is intentionally unaware of the potential support for multiple leagues and therefore only models entities that exist within an individual league.

Class/Interface Description
Division
@Entity
@Table(name = "mys_div")
@Multitenant(MultitenantType.SINGLE_TABLE)
@TenantDiscriminatorColumn(name = "LEAGUE_ID", contextProperty = LEAGUE_CONTEXT)
@NamedQueries({
    @NamedQuery(name="Division.findAll", query="SELECT d FROM Division d ORDER BY d.name",
                hints={@QueryHint(name=QueryHints.QUERY_RESULTS_CACHE, value=HintValues.TRUE)}),
    @NamedQuery(name="Division.findByName", query="SELECT d FROM Division d WHERE d.name = :NAME")
})
public class Division implements Extensible {
Team
@Entity
@Table(name = "mys_team")
@Multitenant(MultitenantType.SINGLE_TABLE)
@TenantDiscriminatorColumn(name = "LEAGUE_ID", contextProperty = LEAGUE_CONTEXT)
@NamedQuery(name="Team.findByDivisionAndName", query="SELECT t FROM Team t WHERE t.name = :NAME AND t.division.name = :DIV")
public class Team implements Extensible {
Player
/**
 * In the MySports demo a Player entity represents an individual member of a
 * team. The Player entity is both multitenant and extensible.
 */
@Entity
@Table(name = "mys_player")
@Multitenant(MultitenantType.SINGLE_TABLE)
@TenantDiscriminatorColumn(name = "LEAGUE_ID", contextProperty = LEAGUE_CONTEXT)
@VirtualAccessMethods
public class Player implements Extensible {
Extensible An application interface used to indicate extensible types and enable their use in the presentation tier. This interface is not required or used by EclipseLink.
Divisions A non-entity container class used for returning multiple divisions from a JAX-RS call to enable the MOXy marshalling into XML.

Persistence

The persistence layer is the main purpose of this example application. The persistence layer makes use of application bootstrapped persistence contexts with support for an EntityManagerFactory and backing ServerSession (with Cache) per league (tenant). This all bootstrapped off of a single persistence-unit definition.


LeagueRepository

The LeagueRepository is the primary persistence abstraction responsible for league (tenant) specific persistence access managing both JPA persistence units and the MOXy JAXBContext.

JPA Usage

The persistence layer makes use of standard JPA 2.0 API plus some EclipseLink specific extensions to support:

  • Multi-tenancy - augment the SQL to limit results to current tenant or leverage Oracle VPD to do SQL augmentation
  • Extensible Entities - support additional tenant specific attributes on entities
  • External Metadata Source - retrieve tenant specific extension definitions for JPA and JAXB from JAX-RS admin service
  • EMF per Tenant: EMF created per tenant with a single shared persistence unit definition
Multi-Tenancy

The configuration that enables multi-tenancy usage is the @Multitenant annotation that is specified on one or more entities. In this example application Player, Team, and Division are multitenant and are each configured using:

@Multitenant(MultitenantType.SINGLE_TABLE)
@TenantDiscriminatorColumn(name = "LEAGUE_ID", contextProperty = LEAGUE_CONTEXT)

This specifies that the entities for multiple tenants are stored in a shared table and that the access to this table must limit its results to a specific tenant using the LEAGUE_ID column and the context property value specified by the LEAGUE_CONTEXT ("mysports.league").

Oracle VPD By default this example application will augment all generated SQL for SELECT, UPDATE, and DELETE to add in an additional comparison for the LEAGU_ID column. With INSERT operations the LEAGUE_ID column will be populated. Alternatively the example application can be configured to use Oracle VPD to handle the SELECT, UPDATE, DELETE SQL additions within the database. To setup and configure the demo application to use Oracle VPD you must be using an Oracle database and must set the mysports.vpd=true in the application's src folder and test's src folder.

Extensible Entities

The entities (Player, Team, and Division) in this example are extensible. This means additional attribute mappings can be dynamically defined. In this case the extensions are tenant specific and the definitions are maintained within the admin application. To make an entity extensible you can use annotations like:

@VirtualAccessMethods
public class Player implements Extensible {

This indicates that the default get and set methods will be used. The Extensible interface is not required by EclipseLink but is used in the application to identify classes that support extensions. Within the entity classes the get and set methods along with a dat structure to store the extended values must be provided.

@Transient
private Map<String, Object> attributes = new HashMap<String, Object>();
 
@SuppressWarnings("unchecked")
public <T> T get(String attributeName) {
    return (T) this.attributes.get(attributeName);
}
 
public Object set(String attributeName, Object value) {
    return this.attributes.put(attributeName, value);
}
External Metadata Source

The extensions definitions are maintained externally in the Admin application which is accessed using JAX-RS calls. The example application provides an implementation of MetadataSource for both JPA and MOXy. For JPA this source is configured using a persistence unit property in the persistence.xml.

<property name="eclipselink.metadata-source" value="example.mysports.admin.AdminMetadataSource"/>
EMF per Tenant

When developing an application that can handle requests from multiple tenants you can choose to have a single EntityManager Factory (EMF) with tenant scoped EntityManagers (EM) or you can choose to have a EMF per tenant. The decision really comes down to the number of tenants and the value of maintaining a cache that can be shared upon user requests for the same tenant and any usage of extended attributes per tenant. In this example application where there extensions per tenant and a limited number of tenants the decision was made to use an EMF per tenant.

Lear more...

JPA-RS

The REST interface for MySports is provided by EclipseLink JPA-RS.

Back to the top