#144
CONTENTS INCLUDE:
n What is EclipseLink n Caching n Query Extensions EclipseLink JPA n Mappings n Connections An Advanced ORM Persistence Framework n Hot Tips and more...
Visit refcardz.com By Gordon Yorke
include implementations of the OSGi specification that support WHAT IS ECLIPSELINK? dynamic access to the Persistence Providers. Download the bundles from http://www.eclipse.org/gemini/jpa/. Focused on standards, EclipseLink delivers a comprehensive open- Within the download, there is a GettingStarted.txt file that will help source Java persistence solution with implementations of Java you work through the details of deploying in an OSGi environment. Persistence API (JPA), Java Architecture for XML Binding (JAXB), and Service Data Objects (SDO). EclipseLink also offers many advanced Weaving features to aid users with their applications. When deployed within a Java EE server or other SPI supporting servers, EclipseLink has an opportunity to enhance the java classes EclipseLink JPA automatically. This enhancement step, referred to as “weaving”,
Get More Refcardz! Refcardz! Get More The focus of this Refcard is EclipseLink’s object to relational allows EclipseLink to provide many optimizations and improve mapping functionality and its extensions of the Java Persistence API functionality. For instance, EclipseLink can offer lazy OneToOne and specification. This card assumes you are already familiar with the Java ManyToOne relationships, on-the-fly change tracking and dynamic Persistence API. fetch groups with weaving. EclipseLink has been JPA 1.0 (JSR 220) certified and is the reference If you are deploying EclipseLink in an environment where weaving implementation for JPA 2.0 (JSR 317). An offshoot of the code base is not automatic (as is the case in Java SE), there are two options for called TopLink Essentials was the reference implementation for JPA enabling weaving. 1.0 (JSR 220). The first and easiest way to enable weaving is to use the -javaagent: How do I get it? Virtual Machine argument providing the location of the eclipselink.jar. Jars and Bundles With the java agent specified, EclipseLink will automatically handle EclipseLink is available in two forms: a single eclipselink.jar file that weaving of the Entities.
contains all that is needed to use any of the EclipseLink functionality java –javaagent:../lib/eclipselink.jar … or OSGi bundles for each of the EclipseLink component modules. The second way to enable weaving is to use the “static weaver”. The Download these from: http://www.eclipse.org/eclipselink/downloads static weaver is a compile time step that is useful in situations where Maven runtime weaving is not available or not desirable. There are many versions and component module bundles available java org.eclipse.persistence.tools.weaving.jpa.StaticWeave -classpath c:\my-pu- jar.jar;
DZone, Inc. | www.dzone.com 2 EclipseLink JPA: An Advanced ORM Persistence Framework
Canonical Metamodel coordinationType Strategy for communicating instance changes to coordinated With Java Persistence API 2.0 came the Criteria API for dynamically nodes. Cache Coordination services must be configured at the defining queries. One of the components of the Criteria API is the EntityManagerFactory level. Canonical Metamodel. The Canonical Metamodel is a collection EclipseLink Cache Types of generated classes whose static attributes allow a query writer to reference strongly typed Entity metadata for the definition of strongly CacheType.FULL Will cache all Entity instances indefinitely. typed Criteria queries. CacheType.SOFT Cache uses SoftReference to hold Entities so Cache size is as large as VM allows. criteriaQuery.from(Employee.class).join(Employee_.phoneNumbers); CacheType.WEAK Cache uses WeakReference to hold entities so cache size Many IDEs, including Eclipse through the Dali project, can generate a is dependent on how many Entities are referenced by the Canonical Metamodel for you. However, if this is unavailable, EclipseLink application. can easily generate these classes during compile time by simply adding CacheType.SOFT_WEAK Recommended. A cache of specific size that uses SoftReference the eclipselink-jpa-modelgen_
Caching provides very efficient data retrieval and can greatly improve Cache Invalidation Policies your application’s performance. Caching is a “first class” feature EclipseLink offers automatic refreshing of Entites based on a time of in EclipseLink and is an integral part of the product. By default, all day or age within the cache. @Cache(expiry=
type cache type. Cache Coordination In an environment where multiple instances of the application isolation Degree to which cached instances are shared with other threads. are deployed, EclipseLink can coordinate the caches of those expiry Invalidates cache entries after a fixed number of milliseconds. applications with simple configuration. With cache coordination, expiryTimeOfDay Invalidates cache entries at specific time of day. active EclipseLink nodes will broadcast either a summary of the alwaysRefresh Update cache with any data retrieved from the database. Generally changes made to an Entity or just the Entity id, for invalidation, to used by queries that can not be executed against the cache. the other connected caches. With this functionality, the number of refreshOnIyIfNewer Used with the above but only refresh if the database version is newer Optimistic Lock exceptions experienced can be reduced, which than the cached version. allows an active application to continue to benefit from caches. disableHits This will force all queries to execute against the database but return results from the cache. Can be used in combination with Cache coordination is activated through Persistence Unit “alwaysRefresh”. properties. First, the protocol is set through
DZone, Inc. | www.dzone.com 3 EclipseLink JPA: An Advanced ORM Persistence Framework
eclipselink.cache.coordination.protocol: cache, the Query cache can be configured for size and to auto-expire.
jms Sends and receives changes through a JMS Topic. The Query Cache can be configured through Query Hints within the Java Persistence API. jms-publish Sends changes through JMS, receive through Message Driven Bean.
rmi Uses a fully connected RMI graph to send and receive changes. eclipselink.query-results-cache Activates the query cache for this query.
rmi-iiop Same as above but uses RMI-IIOP transport protocols. eclipselink.query-results-cache.type Has same cache types as the Entity cache but the default for the Query cache is Additional configuration is completed based on the protocol selected: CacheType.cache.
DZone, Inc. | www.dzone.com 4 EclipseLink JPA: An Advanced ORM Persistence Framework
EclipseLink can build Entity results from the output parameters if the @QueryRedirectors( allQueries=org.queryredirectors.AllQueriesForEntity.class) resultClass or resultSetMapping is set. @Entity public class … The Direction.OUT_CURSOR is used for stored procedure parameters that are returning resultsets through “ref cursors”. Default Redirectors will be called every time a query is executed against this Entity type. Default Redirectors can be configured per If both result sets and output parameters are returned by the Entity by Query type as well. stored procedure, then a SessionEventListener that responds to outputParametersDetected should be registered with the MAPPINGS EntityManagerFactory and the output parameters will be returned through this event. Converters Fetch Groups Sometimes the data in the database column does not match the Lazy attributes can make queries more efficient by delaying the type of the corresponding Entity attribute. EclipseLink can handle loading of data. EclipseLink offers a feature called Fetch Groups that simple conversion for @Basic mappings like Number to String but allows you to define multiple lazy attribute configurations and apply what if the conversion is more complicated? This is where converters those on a per-query basis. Attributes are fully lazy accessible, and can be useful. With a converter, custom bi-directional conversion can accessing an unfetched attribute will cause the Entity attributes to be occur between the database and the Entity attributes. Converters are loaded as per the static lazy configuration from the Entity metadata. supported on @Basic mappings and primitive @ElementCollections. Configuration EclipseLink offers some predefined converters that support Fetch Groups can be created statically using @FetchGroup. commonly occurring conversions:
@FetchGroups({ @FetchGroup( @ObjectTypeConverter Maps column values to attribute values (ie, “t” -> True). name=”FirstLast”, attributes={ @FetchAttribute(name=”first”), @TypeConverter Converts database type to Java type. Useful for ElementCollections. @FetchAttribute(name=”last”) } @StructConverter Converts from Database Struct type. JGeometry has built in support. ), @FetchGroup( name=”LastName”, For truly custom conversions, the @Converter that references an attributes={@FetchAttribute(name=”lastName”)} ) implementation of the org.eclipse.persistence.mappings.converters. }) Converter interface can be specified. They are then applied to the query through the use of Query Hint. Converters can be set directly on the mapping through the query.setHint(QueryHints.FETCH_GROUP_NAME, “FirstLast”); corresponding annotation, or a Converter can be defined at the Entity level and referenced by name through @Convert. If the Fetch Groups can also be created and used at runtime… ElementCollection is a Map type, then a Converter can be applied to FetchGroup fetchGroup = new FetchGroup(); fetchGroup.addAttribute(“lastName”); query.setHint(QueryHints.FETCH_GROUP, fetchGroup); the Map’s Key through @MapKeyConvert.
@TypeConverter( Other Fetch Group query hints are available as well to provide name=”Long2String”, dataType=String.class, fine-grained configuration. Details can be found in the QueryHints objectType=Long.class ) javaDocs. @ObjectTypeConverter( name=”CreditLine”, conversionValues={ Have multiple Persistence Contexts in the same transaction? If @ConversionValue(dataValue=”RB”, objectValue=ROYAL_BANK), Hot any are performing transactional writes, ensure you disable an @ConversionValue(dataValue=”CIB”, EclipseLink optimization with the Entity Manager property eclipselink. objectValue=CANADIAN_IMPERIAL), Tip @ConversionValue(dataValue=”SB”, transaction.join-existing so all queries will access transactional data. objectValue=SCOTTSBANK), @ConversionValue(dataValue=”HD”, objectValue=HALIFAX_DOWNTOWN) } ) Cursors @Entity When reading a large dataset, the application may wish to stream the public class Entity … @ElementCollection results from a query. This is useful if the dataset is quite large. Using @MapKeyColumn(name=”BANK”) @Column(name=”ACCOUNT”) the query hint “eclipselink.cursor” set to “true”, EclipseLink will return @Convert(“Long2String”) @MapKeyConvert(“CreditLine”) a org.eclipse.persistence.queries.CursoredStream, which will allow public Map
Need to load a large dataset and want to bypass the Persistence Interface Attribute Types Hot Context to save heap space? Use the Query Hint “eclipselink.read- If an application has single-valued Entity attributes that are interface Tip only” and the results of the Query will not be managed. types, EclipseLink’s VariableOneToOne mapping can be used to map these attributes as a polymorphic relationship. This mapping type uses a discriminator column similar to Java Persistence API Query Redirectors inheritance support; but, in this case, the discriminator is found on Should an application have the need to dynamically alter a query or the source table. execute a query against another resource, Query Redirectors can @VariableOneToOne( be used. A redirector implements a simple interface org.eclipse. targetInterface=Distributor.class, cascade=PERSIST, persistence.queries.QueryRedirector, and the developer of the fetch=LAZY, discriminatorColumn=@DiscriminatorColumn( Redirector is free to do most anything. Any cache maintenance will name=”DISTRIBUTOR_TYPE”, discriminatorType=INTEGER), have to occur within the Redirector if the query is executed against discriminatorClasses={ @DiscriminatorClass(discriminator=”1”, another resource. value=MegaBrands.class), @DiscriminatorClass(discriminator=”2”, value=Namco.class) Configuration } ) Query Redirectors can be set through the Query Hint eclipselink. public Distributor getDistributor() { query.redirector or set as default Redirectors on an Entity. return distributor; }
DZone, Inc. | www.dzone.com 5 EclipseLink JPA: An Advanced ORM Persistence Framework
To execute queries with path expressions that include an interface authentication or row level security is required, EclipseLink has mapping, a Query Key must be defined on the Interface descriptor. easy-to-use configuration that will allow “authentication” of the Currently, this must done using a SessionCustomizer. Details on connection. Query Keys can be found here: http://wiki.eclipse.org/EclipseLink/ UserGuide/JPA/Basic_JPA_Development/Querying/Query_Keys For Proxy Authentication, provide the necessary Persistence Unit properties to the EntityManagerFactory or EntityManager and Additional Filtering Criteria EclipseLink will ensure the connection acquired from the datasource Need to support multi-tenancy, temporal filtering or any number will be “authenticated”. of other use cases where an application has a query restriction Map emProperties = new HashMap(); emProperties.put(“eclipselink.oracle.proxy-type”, that needs to be applied to the restrictions on all queries? OracleConnection.PROXYTYPE_USER_NAME); emProperties.put(OracleConnection.PROXY_USER_NAME, “john”); @AdditionalCriteria can be applied to an Entity class to specify EntityManager em = emf.createEntityManager(emProperties); that additional filtering occurs for any queries on that type. When specifying the path in an AdditionalCriteria, the identification Or in the case of injection: variable “this” is used to identify the root of the query. entityManager.setProperty(“eclipselink.oracle.proxy-type”, OracleConnection.PROXYTYPE_USER_NAME); @AdditionalCriteria(“this.role = :accessRole”); entityManager.setProperty(OracleConnection.PROXY_USER_NAME, “john”); @Entity public class EntityA {…} For Virtual Private Database (VPD) or manual “authentication”, Additional Criteria supports parameters, and parameter values can a Session Event exists “postAcquireExclusiveConnection” that be set at the EntityManagerFactory or EntityManager levels. will be called whenever EclipseLink acquires a connection for “authentication”. This event can be used to provide any required entityManager.setProperty(“accessRole”, “bravo”); details to the connection like a ClientIdentifier. An additional property that specifies when EclipseLink must use the Hot Combine Additional Criteria with @Noncacheable relationships to “authenticated” connection is required for both VPD type and Proxy Tip provide EntityManager scoped user data. authentication. “eclipselink.jdbc.exclusive-connection.mode” should be set to “Isolated” if all Entities corresponding to secured tables have been set to @Cacheable(false) or to “Always” otherwise . Return On Insert/Update Connection Pooling If the database has triggers that return data to the calling client, the When deploying an EclipseLink application in an environment @ReturnInsert / @ReturnUpdate annotations can be applied to the without managed datasources, EclipseLink offers built-in connection corresponding @Basic mappings to have EclipseLink apply the return management. Configuring connection pooling can be as simple as value to the Entity. setting the Persistence Unit Properties using “eclipselink.connection- The result from the database will be parsed for the mappings field pool. “ during creation of the Entity Manager Factory. There are many and the value placed in the attribute. connection pool properties combinations that can be found in the
@ReturnInsert(returnOnly=true) JavaDocs. @Basic protected long id; OTHER POPULAR EXTENSIONS CONNECTIONS Persistence Context Memory Management Partitioning If a Persistence Context tends to have a long lifecycle within an If an application needs access to multiple databases (perhaps for application, managing the size of the Persistence Context can be load balancing or data affinity), EclipseLink has functionality called difficult. EclipseLink can allow an application to leverage the Java Partitioning that will allow many schemes for accessing multiple garbage collector and remove Entities from the Persistence Context databases. that are no longer in use by the application. This is done through the EntityManager property “eclipselink.persistence-context.reference- With partitioning, users can “stripe” data across multiple databases mode”. Possible values are: or schemas by Entity field value or by Entity type. • HARD - the default and ensures no Entities will be removed from the Persistence Context @RangePartitioning, @HashPartitioning, @PinnedPartitioning, @ValuePartitiong automatically. • WEAK – in combination with weaving, ensures any Entities with changes will not be removed Other Partitioning Policies are available for load balancing or from Persistence Context; but other unreferenced Entities may be removed. replication across multiple databases or schemas. • FORCED_WEAK – any unreferenced Entities may be removed from the Persistence Context by the garbage collector. Changes in these Entities will be lost if not already flushed. @ReplicationPartititoning, @RoundRobinPartitioning, @UnionPartitioning
Entirely custom policy implementations are also an option. If users Batch Writing need certain processing that can not be found in the pre-existing EclipseLink supports writing to the database using batched writes. partitioning implementations the PartitioningPolicy can be extended This is configured through the Persistence Unit property “eclipselink. and a custom Policy specified using @Partitioning. jdbc.batch-writing” and should be used in combination with parameter binding, which is active by default. Possible values for the An example of an Entity’s partitioning configuration follows: property are: @Entity @Table(name = “PART_DEPT”) • JDBC – this uses standard JDBC batch writing and should be used in most cases. @HashPartitioning( name=”HashPartitioningByID”, • Oracle-JDBC – use native Oracle database batch writing. partitionColumn=@Column(name=”ID”), unionUnpartitionableQueries=true, connectionPools={“node2”, “node3”}) Customizers @UnionPartitioning( name=”UnionPartitioningAllNodes”, EclipseLink has a great depth to its functionality. Although the most replicateWrites=true) @Partitioned(“HashPartitioningByID”) popular features are available, not all of the EclipseLink functionality public class Department implements Serializable { is exposed through JPA extensions. “Customizers” are a simple mechanism that exposes internal EclipseLink customization to Java VPD, Proxy Authentication Persistence API applications. If an application needs to access a database when proxy
DZone, Inc. | www.dzone.com 6 EclipseLink JPA: An Advanced ORM Persistence Framework
Both EntityManagerFactory level customizers, called Session that is used for VPD; transaction events like preRollbackTransaction; Customizers, and Entity level mapping customizers, called Descriptor EntityManager process events like postCalculateChanges that are Customizers, are available. fired after flush but before writes have begun; query execution events like outputParametersDetected for Stored Procedure execution; and To use a Session Customizer, the Persistence Unit property many more events. “eclipselink.session.customizer” is used to specify an implementor of the interface org.eclipse.persistence.config.SessionCustomizer. To receive notification of these events, a custom class is created that implements org.eclipse.persistence.sessions.SessionEventListener To use a Descriptor Customizer, a Persistence Unit property or extends org.eclipse.persistence.sessions.SessionEventAdaptor “eclipselink.descriptor.customizer.
ABOUT THE AUTHOR RECOMMENDED BOOK Gordon Yorke is an EclipseLink Architecture Council Pro JPA 2 is a detailed learning and use reference, member and committer, JSR 317 & JSR 338(JPA 2.0 & written by EJB co-spec lead and JPA contributor Mike 2.1) Expert Group member and a long time developer Keith and his colleague. of EclipseLink and its past permutations. With over 11 years of ORM framework experience Gordon brings a wealth of knowledge on object-relational persistence, data-access and caching.
#82
CONTENTS INCLUDE:
■ Browse our collection of over 100 Free Cheat Sheets About Cloud Computing ■ Usage Scenarios Getting Started with dz.com ■ Underlying Concepts ■ Cost ... ® efcar ■ #64 Data Tier Technologies . Cloud Computing omply brought■ Platform to you Management by and more... e. C . Collaborat
isit r isit AldonChange By Daniel Rubio V
dz! also minimizes the needCONTENTS to make designINCLUDE: changes to support ABOUT CLOUD COMPUTING one time events. ■ HTML Basics dz.com ■ Upcoming Refcardz HTML vs XHTML Web applications have always been deployed on servers Automated growth & scalable technologies ■ Validation connected to what is now deemed the ‘cloud’. Having the capability■ to support one time events, cloud efcar
e Refcar Useful Open Sour computing platforms also facilitate the gradual growth curves ■ Page Structur #84 However, the demands and technology used on such servers ce T faced by web applications.■ ools isit r Key Structural Elementse Elements and m E: has changed substantiallyBy Paul in recent M. years, Duvall especially with V
the entrance of service providers like Amazon, Google and Large scale growth scenarios involving specialized equipment Integration Continuous Integration: CONTENTS INCLUD Microsoft. (e.g. load balancers and clusters) are all but abstractedore... away by Patterns and Anti-Patternse changes dz! Continuous Delivery ■ e at Every Change About Continuous rns orkspace to isolat relying on a cloud computing platform’s technology. Cor ■ Build Softwar Description e in a Private W epository HTML BASICS These companies have long deployedntrol r web applications
■ Patterns and Anti-patteol Develop softwar rging and to manage dz.com n that adapt and scale to large user bases, making them In addition, several cloud computing platforms support data e Patter fi les to a version-co ■ HTML Version Contr HTML and XHTML ar more... orkspaceknowledgeableCommit allin manyline aspects to minimize r meelated to cloud computing. tier technologies that exceed the precedent set by Relational ■ Build Management Private W hat utilizes multiple e Refcar HTML is used as the graphical user interface in client-side
Develop on a main Database Systems (RDBMS): Map Reduce,e the foundationweb service of APIs,all web development. efcar ■ Build Practices and Repository active code lines e within a system t ts of work pr TION This Refcard will introducear to you to cloud computing, with an etc. Some platformsograms support written lar gein JavaScript.scale RDBMS Server deployments. The sr By CSS3 e Mainline Developing softw by task-oriented uni and Java also r c attribute describes wher Andy Harris war Get Mor emphasis on these providers, so you can better understand codelines and the alt attribute describes alternate text that is displayed if
ask Level Commit isit r isit ce code changes ol as the output mechanism.eceive data The fr emer what it is a cloudganize computing sour es as aplatform T can offer your web the image is unavailable.
V ocess of building soft Codeline Policy Or ce without likewise use HTML and XHTML as their visual-side engine. languages HTML like PHP e the image Get Mor om web pages and use HTML s version contr applications.it and submit chang h unique name e from sour CLOUD COMPUTING PLATFORMS AND ABOUT CONTINUOUS INTEGRAoject’ was once a very loosely-defi Nested tags file can be found,
tion (CI) is the pr e.com Task-Level Comm Label the build wit ies to build softwar re minimum UNDERLYING CONCEPTS
dz! dz! oblem ging Ajax technologies T standar ags can be (and fr committed to a pr USAGE SCENARIOSAutomate all gurationactivit pendencies to the ba dization, but as it has become mor Continuous Integra Label Build manual confi same deployment need for standar ned language with very little cannot overlap, so zon onment , a solution to a pr e-installed tool de equently ar NoSQL blem) target envir Amazon EC2: Industry standard software and virtualization b> with every change. Automated Build Reduce pr whether you chooseds tohas write become HTML mor or XHTML, understanding e) nested inside each other patterns (i.e. ns (i.e., ineffective .d deployment, use the is fi epository Pay onlyncies what you consumeAR or EAR) in each Amazon’s cloudthe curr computing platform is heavily based on ne. r For each tagged e important, the
x” the particulare solutions pro thatuce Web application deployment until a few years agoonment was similar ent standar e appar is not legal, but e Refcar e xt) and anti-patter Minimal Depende package (e.g. W dent libraries get envir industry standarthat willd simplifysoftwar alle and your virtualization other web coding. technology Fortunately. HTML erns ar ent. Regar HTML VS XHTML . T CI can be explained via s used to “fi t can fi le that all tar ds will help you pr ags Binaryto Integrity most phone services:Centralize plans all depen withte alloted resources, with an and XHTML ar Get Mor Get appear to befects. bene They aresults when compa The various resources consumed by web applicationsly, continually (e.g. Every page (HTML or XHTML shar Perform a Private velopment team individual operating system sinstances. Browser manufactur adverse ef egration Staged Builds Repository tion Build periodical common.) All ar bandwidth, memory, CPU) are tallied on aom per CI server-unit to basis de web developers came up with clever workar produce unintended r Private Build Perform an Integra edback fr extension. HTML ers added many competing estandar than anybody Refcard (starting from zero) by all major cloud computing platforms. As a user of Amazon’s eEC2 essentially cloud computing plain text platform, you are result is a lack of standar ation term Continuous Int y occur es certain elements in the pattern. ch as Send automated fe ith builds based on processor ors as soon as the assigned an operating systemfiles should in the not same be cr way as on all hosting The latest web standar tional use of thend test” cycle, this Integration Build er documentation w e.com Continuous Integr clude concepts su While the convenefers to the n“build of CI ato in Generate develop expands on the notio DZone, Inc. Cloud Computing 140 Preston Executive Dr. Suite 100 Cary, NC 27513 DZone communities deliver over 6 million pages each month to 888.678.0399 more than 3.3 million software developers, architects and decision 919.678.0300 makers. DZone offers something for everyone, including news, Refcardz Feedback Welcome tutorials, cheat sheets, blogs, feature articles, source code and more. [email protected] “DZone is a developer’s dream,” says PC Magazine. $7.95 Sponsorship Opportunities Copyright © 2011 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, [email protected] Version 1.0 without prior written permission of the publisher.