• Like
  • Save
Overview of JPA (Java Persistence API) v2.0
Upcoming SlideShare
Loading in...5
×
 

Overview of JPA (Java Persistence API) v2.0

on

  • 3,579 views

JPA (Java Persistence API) is a JCP Standard for Object-Relational Mapping (ORM) persistence for the Java platform, both JavaSE and JavaEE. This talk will discuss and show examples from the latest ...

JPA (Java Persistence API) is a JCP Standard for Object-Relational Mapping (ORM) persistence for the Java platform, both JavaSE and JavaEE. This talk will discuss and show examples from the latest version of the spec: JPA v2.0. Based upon influences from a variety of technologies that competed with the original JavaEE EJB specification for Entity beans, JPA promotes the use of light-weight POJO-based Entity objects and a simple EntityManger interface to control the CRUD operations to the backend RDBMS. Even with the rise of NoSQL data stores, there are still many applications that are well suited to a relational database solution and JPA is my favorite ORM tool for Java development.

In the talk I will present:
* Entities
* Entity Operations
* Query Language
* Containers & Deployment
* "In Practice" common problems, solutions and patterns of use

Statistics

Views

Total Views
3,579
Views on SlideShare
3,551
Embed Views
28

Actions

Likes
4
Downloads
193
Comments
0

6 Embeds 28

http://www.techgig.com 18
http://www.linkedin.com 4
http://115.112.206.131 3
http://www.slashdocs.com 1
https://twitter.com 1
https://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Overview of JPA (Java Persistence API) v2.0 Overview of JPA (Java Persistence API) v2.0 Presentation Transcript

    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Overview of JPA v2.0 (Java Persistence API) Entities Entity In Practice Operations Overview of JPA v2.0 Containers & Query Deployment Language Bryan Basham Software Alchemy basham47@gmail.com http://www.linkedin.com/in/SoftwareAlchemistBryan Basham – Overview of JPA v2.0 Slide 1
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy History ● Java v1.1 (1997) included JDBC ● J2EE v1.2 (1999) introduced EJB Entity beans ● Entity beans sucked, so others did it better – iBATIS (2001) – Hibernate (2001) – JDO (JSR 12, final in 2002) ● JPA v1.0 (JSR 220) was released in 2006 ● JPA v2.0 (JSR 317) was released in 2009Bryan Basham – Overview of JPA v2.0 Slide 2
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Who Needs a Standard? ● JPA provides a flexible standard ● Multiple, competing implementations – DataNucleus – EclipseLink – Hibernate – ObjectDB – OpenJPABryan Basham – Overview of JPA v2.0 Slide 3
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Typical Architecture #1 Your Standalone Application JPA Spring (optional) Hibernate EclipseLink OpenJPA (plus optional libs) Java Lang / JRE JDK The Java Virtual MachineBryan Basham – Overview of JPA v2.0 Slide 4
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Typical Architecture #2 Your Enterprise Application JPA Java EE Spring (servlets, JSP, JSF, EJB, JNDI, etc.) (optional) Hibernate (plus optional libs) Java Lang / JRE JDK The Java Virtual MachineBryan Basham – Overview of JPA v2.0 Slide 5
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entities Relationships Keys Inheritance Beans & DB Mappings Properties Entities Entity In Practice Operations Overview of JPA v2.0 Containers & Query Deployment LanguageBryan Basham – Overview of JPA v2.0 Slide 6
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Classes ● Any POJO, but should be a Java Bean ● Class must not be final; nor methods or persistence instance variables ● May be Serializable and be passed across remote calls, such as RMI ● Entities may exist in a class hierarchy ● Queries may be polymorphicBryan Basham – Overview of JPA v2.0 Slide 7
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Classes: Example «entity» import javax.persistence.Basic; Employee import javax.persistence.Entity; firstName : String @Entity /** Not fully baked */ lastName : String age : Integer public class Employee { @Basic(optional=false) private String firstName; @Basic(optional=false) private String lastName; @Basic(optional=false) private Integer age; public String getFirstName() { return firstName; } public void setFirstName(String name) { this.firstName = name; } public String getLastName() { return lastName; } public void setLastName(String name) { this.lastName = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }Bryan Basham – Overview of JPA v2.0 Slide 8
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Access Types ● Access to DB fields can be on instance variables or properties ● You can specific the access type with an annotation: @Entity @Access(AccessType.PROPERTY) public class Employee { /* entity code */ } ● If no access type is defined, then the default type (by usage) applies to the whole entity class hierarchyBryan Basham – Overview of JPA v2.0 Slide 9
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Classes: Example #2 // assume all necessary imports from now on @Entity @Access(AccessType.PROPERTY) public class Employee { private String _firstName; private String _lastName; private Integer _age; @Basic(optional=false) public String getFirstName() { return _firstName; } public void setFirstName(String name) { this._firstName = name; } @Basic(optional=false) public String getLastName() { return _lastName; } public void setLastName(String name) { this._lastName = name; } @Basic(optional=false) public Integer getAge() { return _age; } public void setAge(Integer age) { this._age = age; }Bryan Basham – Overview of JPA v2.0 Slide 10
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Data Types ● A property data type can be: – any Java primitive – any Java primitive wrapper – Strings – Dates – Big integer and decimals – Byte arrays (for BLOBs) – Character arrays (for CLOBs) – Enum valuesBryan Basham – Overview of JPA v2.0 Slide 11
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Enum Types «entity» «enumeratedType» Employee Gender gender : Gender firstName : String +MALE lastName : String +FEMALE @Entity age : Integer public class Employee { public enum Gender { MALE, FEMALE } @Basic(optional = false) Enum ordinal private Gender gender; @Basic(optional=false) private String firstName; @Basic(optional=false) private String lastName; @Basic(optional=false) private Integer age;Bryan Basham – Overview of JPA v2.0 Slide 12
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Derived Properties «entity» @Entity Employee public class Employee { firstName : String lastName : String @Basic(optional=false) dateOfBirth : Date private String firstName; #age : Integer @Basic(optional=false) private String lastName; @Basic(optional=false) private Date dateOfBirth; @Transient private Integer age; public Integer getAge() { if ( this.age == null ) { this.age = DateUtils.dateDiffYears(new Date(), this.dateOfBirth); } return age; }Bryan Basham – Overview of JPA v2.0 Slide 13
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Embeddable Properties ● Useful for representing small, non-entity classes ● Thus supports DDD Value Object concepts (well, almost) ● Also supports Composition without the need for cascading deletes (fields are embedded within the owning entity table) ● One Embeddable can embed other EmbeddablesBryan Basham – Overview of JPA v2.0 Slide 14
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Embeddable Properties (2)@Embeddablepublic class PhoneNumber { @Basic(optional=false) private String areaCode; // unfortunately, cant make these final @Basic(optional=false) private String localNumber; @Basic(optional=true) private String extension; public PhoneNumber() { /* no-arg ctor for JPA */ } public PhoneNumber(String areaCode, String localNumber, String extension) { this.areaCode = areaCode; this.localNumber = localNumber; this.extension = extension; } public String getAreaCode() { return areaCode; } public String getLocalNumber() { return localNumber; } public String getExtension() { return extension; }}Bryan Basham – Overview of JPA v2.0 Slide 15
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Embeddable Properties (3) «entity» 1 «valueObject» Employee officePhone PhoneNumber firstName : String areaCode : String lastName : String localNumber : String dateOfBirth : Date extension : String #age : Integer officePhone : PhoneNumber @Entity public class Employee { Fields of the Embeddable @Embedded are embedded directly into private PhoneNumber officePhone; the table of the owning Entity.Bryan Basham – Overview of JPA v2.0 Slide 16
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Embeddable Properties (4) «entity» 1 «valueObject» type Employee PhoneNumber firstName : String areaCode : String lastName : String localNumber : String dateOfBirth : Date extension : String #age : Integer Entity FK Map key phones : Map<String, PhoneNumber> @Entity public class Employee { Due to the one-to-many the embeddables are stored @Embedded in a separate table. @ElementCollection(fetch = FetchType.LAZY) private Map<String,PhoneNumber> phones = new HashMap<String,PhoneNumber>();Bryan Basham – Overview of JPA v2.0 Slide 17
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Keys ● Every entity must have a primary key ● Key is specified with the @Id annotation ● Only one key defined for a given entity class hierarchy ● Keys can be simple or composite ● Simple key (or properties of a composite key) must have a simple data type: – Strings, Java primitives (or wrappers), dates, or big numbersBryan Basham – Overview of JPA v2.0 Slide 18
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Keys: Example «entity» @Entity Employee public class Employee { SSN : String @Id @Basic(optional=false) firstName : String // SSN must be unique (not a good choice) lastName : String private String SSN; dateOfBirth : Date #age : Integer @Basic(optional=false) private String firstName; @Basic(optional=false) private String lastName; @Basic(optional=false) private Date dateOfBirth; @Transient private Integer age;Bryan Basham – Overview of JPA v2.0 Slide 19
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Keys: Example #2 «entity» @Entity Employee public class Employee { id : Long @Id @GeneratedValue firstName : String // let the DBMS assign the key on insert lastName : String private Long id; dateOfBirth : Date #age : Integer @Basic(optional=false) private String firstName; MySQL uses autoincrement for key generation. @Basic(optional=false) private String lastName; @Basic(optional=false) private Date dateOfBirth; @Transient private Integer age;Bryan Basham – Overview of JPA v2.0 Slide 20
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Associations ● Entities can be associated to other Entities and Embeddable objects ● Collections (bags), sets, sorted sets, lists, and even maps ● One-to-one, one-to-many, many-to-one, and many-to-many ● Uni- and bi-directional relationships ● Lazy and Eager fetching techniquesBryan Basham – Overview of JPA v2.0 Slide 21
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy One-to-One «entity» 1 1 «entity» User employee Employee id : Long id : Long userName : String firstName : String password : String lastName : String employee : Employee dateOfBirth : Date #age : Integer @Entity public class User { @Id @GeneratedValue private Long id; @Basic(optional=false) private String userName; @Basic(optional=false) private String password; @Basic(optional=false) @OneToOne(fetch=FetchType.EAGER) private Employee employee;Bryan Basham – Overview of JPA v2.0 Slide 22
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy One-to-One (2) private void createExampleUser() { Calendar cal = Calendar.getInstance(); try { em.getTransaction().begin(); Employee emp = new Employee(); emp.setGender(Gender.MALE); emp.setFirstName("Bryan"); emp.setLastName("Basham"); cal.set(1964, 7, 22); emp.setDateOfBirth(cal.getTime()); em.persist(emp); // NOTE: need to persist all entities User u1 = new User(); u1.setUserName("bbasham"); u1.setPassword("guess"); u1.setEmployee(emp); em.persist(u1); em.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); em.getTransaction().rollback(); } }Bryan Basham – Overview of JPA v2.0 Slide 23
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy One-to-Many «entity» 1 0..* «entity» Department staff Employee id : Long id : Long name : String firstName : String staff : Set<Employee> lastName : String dateOfBirth : Date #age : Integer @Entity public class Department { @Id @GeneratedValue private Long id; @Basic(optional = false) private String name; @OneToMany(fetch = FetchType.LAZY) private Set<Employee> staff;Bryan Basham – Overview of JPA v2.0 Slide 24
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Many-to-Many «entity» 0..* 0..* «entity» Project projects team Employee id : Long id : Long name : String firstName : String team : Set<Employee> lastName : String dateOfBirth : Date #age : Integer projects : Set<Project>Bryan Basham – Overview of JPA v2.0 Slide 25
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Many-to-Many (2) @Entity public class Project { @Id @GeneratedValue private Long id; @Basic(optional = false) private String name; @ManyToMany(fetch = FetchType.LAZY) private Set<Employee> team; @Entity The mappedTo value public class Employee { specifies that the Project entity is the “owner” of the relationship. @Id @GeneratedValue private Long id; // Skipping basic properties @ManyToMany(fetch = FetchType.LAZY, mappedTo=”team”) private Set<Project> projects;Bryan Basham – Overview of JPA v2.0 Slide 26
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Many-to-Many (3) Project FK Employee FKBryan Basham – Overview of JPA v2.0 Slide 27
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Inheritance ● JPA supports flexible Entity inheritance ● A Entity may be an abstract class ● An Entity class can extend a non-Entity class ● A non-Entity class can extend an Entity class ● Queries can be written to any Entity classes ● Three DB mapping strategies: – SINGLE_TABLE (the default) – JOINED – TABLE_PER_CLASS (not required per spec)Bryan Basham – Overview of JPA v2.0 Slide 28
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Inheritance Example «entity» 1 AbstractGame game1 id : Long 1 team1Score : int game2 team2Score : int getTeam1() : Team «entity» getTeam2() : Team getWinner() : Team Team 1 1 team2 team1 «entity» «entity» IntermediateGame StartingTeam game1 : AbstractGame team1 : Team game2 : AbstractGame team2 : TeamBryan Basham – Overview of JPA v2.0 Slide 29
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Single Table Example @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn( name="game_type" ) public abstract class AbstractGame { @Id @GeneratedValue private Long id; @Basic(optional=false) private Integer team1Score; @Basic(optional=false) private Integer team2Score; @Entity @DiscriminatorValue("SG") public class StartingGame extends AbstractGame { @Basic(optional=false) private Team team1; @Basic(optional=false) private Team team2; @Entity @DiscriminatorValue("IG") public class IntermediateGame extends AbstractGame { @Basic(optional=false) private AbstractGame game1; @Basic(optional=false) private AbstractGame game2;Bryan Basham – Overview of JPA v2.0 Slide 30
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Single Table Example (2) AbstractGame IntermediateGame discriminator StartingGame fieldBryan Basham – Overview of JPA v2.0 Slide 31
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Joined Example @Entity @Inheritance(strategy=InheritanceType.JOINED) public abstract class AbstractGame { @Id @GeneratedValue private Long id; @Basic(optional=false) private Integer team1Score; @Basic(optional=false) private Integer team2Score; @Entity public class StartingGame extends AbstractGame { @Basic(optional=false) private Team team1; @Basic(optional=false) private Team team2; @Entity public class IntermediateGame extends AbstractGame { @Basic(optional=false) private AbstractGame game1; @Basic(optional=false) private AbstractGame game2;Bryan Basham – Overview of JPA v2.0 Slide 32
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Joined Example (2) AbstractGame IntermediateGame StartingGameBryan Basham – Overview of JPA v2.0 Slide 33
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Database Mappings ● JPA implementations like Hibernate can dynamically create a DB schema for RAD ● But if you have an existing schema, then you can use annotations to map: – Entity classes to tables – Entity properties to fields – Join columns of relationships – ...and moreBryan Basham – Overview of JPA v2.0 Slide 34
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Domain Model Example «entity» Department id : Long name : String staff : Set<Employee> 1 department 0..* staff «entity» 1 1 «entity» 1 «valueObject» type User employee Employee PhoneNumberid : Long firstName : String areaCode : StringuserName : String lastName : String localNumber : Stringpassword : String dateOfBirth : Date extension : Stringemployee : Employee #age : Integer phones : Map<> projects : Set<Project> user : User department : Department 0..* team 0..* projects «entity» Project id : Long name : String Bryan Basham – Overview of JPA v2.0 team : Set<Employee> Slide 35
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy ER Diagram «table» «table» «table» USR EMP DEPTSID : BIGINT(20) SID : BIGINT(20) SID : BIGINT(20)NAME : VARCHAR(32) FNAME : VARCHAR(100) NAME : VARCHAR(64)PW : VARCHAR(16) LNAME : VARCHAR(100)EMP_SID : NUMBER(20) DOB : DATETIME GEN_CODE : VARCHAR(6) «table» «table» EMP_PHONE PRJ_EMP EMP_SID : BIGINT(20) PRJ_SID : BIGINT(20) TYPE : VARCHAR(7) EMP_SID : BIGINT(20) AREA_CODE : CHAR(3) NUMBER : CHAR(4) EXT : CHAR(3) «table» PRJ SID : BIGINT(20)Bryan Basham – Overview of JPA v2.0 NAME : VARCHAR(64) Slide 36
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Basic DB Mappings @Entity @Table(name="EMP") public class Employee { @Id @GeneratedValue @Column(name="SID") private Long id; @Basic(optional = false) @Column(name="GEN_CODE", length=6) @Enumerated(value=EnumType.STRING) private Gender gender; @Basic(optional=false) @Column(name="FNAME", length=100) private String firstName; @Basic(optional=false) @Column(name="LNAME", length=100) private String lastName;Bryan Basham – Overview of JPA v2.0 Slide 37
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Relationship Mappings @Entity @Table(name="USR") public class User { @Id @GeneratedValue @Column(name="SID") private Long id @Basic(optional = false) @Column(name="NAME", length=32, unique=true) private String userName; @Basic(optional = false) @Column(name="PW", length=16) private String password; @Basic(optional = false) @OneToOne(fetch = FetchType.EAGER, cascade={CascadeType.ALL}) @JoinColumn(name="EMP_SID") private Employee employee;Bryan Basham – Overview of JPA v2.0 Slide 38
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Relationship Mappings (2) @Entity @Table(name = "PRJ") public class Project { @Id @GeneratedValue @Column(name = "SID") private Long id; @Basic(optional = false) @Column(name = "NAME", length=64) private String name; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "PRJ_EMP", joinColumns = { @JoinColumn(name = "PRJ_SID", referencedColumnName = "SID") }, inverseJoinColumns = { @JoinColumn(name = "EMP_SID", referencedColumnName = "SID") }) private Set<Employee> team = new HashSet<Employee>();Bryan Basham – Overview of JPA v2.0 Slide 39
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Embeddable Mappings @Entity @Table(name="EMP") public class Employee { @Embedded @ElementCollection(fetch = FetchType.LAZY) @CollectionTable(name="EMP_PHONE", joinColumns={ @JoinColumn(name="EMP_SID", referencedColumnName="SID") }) @MapKeyColumn(name="PHONE_TYPE") private Map<String, PhoneNumber> phones = new HashMap<String, PhoneNumber>(); @Embeddable public class PhoneNumber { @Column(name="AREA_CODE", length=3) private String areaCode; @Column(name="NUMBER", length=7) private String localNumber; @Column(name="AREA_CODE", length=3, nullable=true) private String areaCode;Bryan Basham – Overview of JPA v2.0 Slide 40
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Operations Relationships Keys Inheritance Beans & DB Mappings Properties Entities EntityManager CRUD Ops Entity In Practice Operations Other operations Overview of JPA v2.0 Containers & Query Deployment LanguageBryan Basham – Overview of JPA v2.0 Slide 41
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Manager «class» Persistence {from javax.persistence} createEntityManager- Factory(String puName) : EMF «interface» EntityManagerFactory {from javax.persistence} createEntityManager() : EM .... .. «interface» ..... .... EntityManager META-INF/persistence.xml {from javax.persistence} persist(entity:Object) : void find(eCls:Class<T>, key:Object) : T merge(entity:T) : T remove(entity:Object)Bryan Basham – Overview of JPA v2.0 Slide 42
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy CRUD Operations ● Create: – Just create an Entity POJO with no id – Call em.persist(entity); JPA populates id ● Retrieve: – Employee emp = em.find(Employee.class, 47L); ● Update: – Create POJO with id; call em.merge(entity) ● Delete: – Create POJO with id; call em.remove(entity)Bryan Basham – Overview of JPA v2.0 Slide 43
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Persisting Relationships ● By default, you must persist all parts by hand – Remember our example: // Make and persist an employee Employee emp = new Employee(); // setters skipped em.persist(emp); // Make and persist a user User user = new User(); // setters skipped user.setEmployee(emp); em.persist(user); ● You can tell JPA to persist parts with many relationship annotationsBryan Basham – Overview of JPA v2.0 Slide 44
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Cascading Operations @Entity public class User { @Id @GeneratedValue private Long id; @Basic(optional=false) private String userName; @Basic(optional=false) private String password; @Basic(optional=false) @OneToOne(fetch=FetchType.EAGER , cascade={CascadeType.ALL}) private Employee employee; private void createExampleUser() { em.getTransaction().begin(); // Make an employee Employee emp = new Employee(); // setters skipped // Make a user User user = new User(); // setters skipped user.setEmployee(emp); // Persist the User and the Employee is automatically saved em.persist(user);Bryan Basham – Overview of JPA v2.0 Slide 45
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Other EM Operations ● flush() – Saves EM context state to DB ● detach(entity) – Detaches an Entity from EM context ● refresh(entity) – Refreshes the Entity state from the DB ● getReference(id):T – Retrieves a lazy Entity from the DBBryan Basham – Overview of JPA v2.0 Slide 46
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Query Language Relationships Keys Inheritance Beans & DB Mappings Properties Entities EntityManager CRUD Ops Entity In Practice Operations Other operations Overview of JPA v2.0 SELECT Query Parameters Containers & Query Expressions Deployment Language Joins UPDATE & SELECT Clause DELETEBryan Basham – Overview of JPA v2.0 Slide 47
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy SELECT Statements ● Like SQL SELECT statements; except it selects a whole Entity object ● Examples: – SELECT e FROM Employee AS e – SELECT e FROM Employee AS e JOIN e.projects p WHERE p.name = Cobia ● Code: String statement = "SELECT e FROM Employee AS e"; TypedQuery<Employee> query = em.createQuery(statement, Employee.class); List<Employee> list = query.getResultList();Bryan Basham – Overview of JPA v2.0 Slide 48
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Query Parameters ● Supports JDBC-like indexed parameters: private List<Employee> queryTeam(Project project) { String statement = "SELECT e FROM Employee AS e JOIN e.projects p WHERE p.name=?"; TypedQuery<Employee> query = em.createQuery(statement, Employee.class); query.setParameter(1, project.getName()); return query.getResultList(); } ● Also supports named parameters: private List<Employee> queryTeam(Project project) { String statement = "SELECT e FROM Employee AS e JOIN e.projects p WHERE p.name=:PRJ"; TypedQuery<Employee> query = em.createQuery(statement, Employee.class); query.setParameter("PRJ", project.getName()); return query.getResultList(); }Bryan Basham – Overview of JPA v2.0 Slide 49
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Conditional Expressions ● Literals ● Functions ● Basic Operators ● Collection Operators ● Path expressionsBryan Basham – Overview of JPA v2.0 Slide 50
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Literals ● Strings: string and strings ● Boolean: TRUE and FALSE ● Numbers: both Java and SQL literals ● Dates: {d 2011-10-11} – This syntax is handled by the JDBC provider – The JPA provider is not required to mediate ● Enums: org.basham.TestJPA.entities.Gender.MALE – Probably best to just pass in as a parameterBryan Basham – Overview of JPA v2.0 Slide 51
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Functions ● Strings: CONCAT, SUBSTRING, TRIM, UPPER, LOWER, LENGTH, LOCATE ● Numeric: ABS, SQRT, MOD, SIZE(collection), INDEX(item in a List) ● Temporal: CURRENT_DATE, CURRENT_TIME, and CURRENT_TIMESTAMP ● CASE statement ● Entity Type: TYPE(game) = StartingGameBryan Basham – Overview of JPA v2.0 Slide 52
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Basic Operators ● Comparison: <, <=, =, <>, >, >= ● Arithmetic: +, -, *, / ● Logical: NOT, AND, and OR ● Between: x [NOT] BETWEEN y AND z ● String matching: x [NOT] LIKE B% ● Null check: x IS [NOT] NULLBryan Basham – Overview of JPA v2.0 Slide 53
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Collection Operators ● Fixed membership: – a [NOT] IN (x, y, z, ...) ● Empty: – collection IS [NOT] EMPTY ● Flexible membership: – entity [NOT] MEMBER [OF] collection private List<Employee> queryTeam(Project project) { String st = "SELECT e FROM Employee e WHERE :PRJ MEMBER OF e.projects"; TypedQuery<Employee> query = em.createQuery(st, Employee.class); query.setParameter("PRJ", project); return query.getResultList(); }Bryan Basham – Overview of JPA v2.0 Slide 54
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Path Expressions ● Allows simple object navigation – OneToOne and ManyToOne relationships – Single Embedded properties (no collections) ● Examples: – How many Employees with short passwords? SELECT count(e) FROM Employee e WHERE LENGTH(e.user.password) <= 4 – How many Employees with office phones in Rochester? SELECT count(e) FROM Employee e WHERE e.officePhone.areaCode = 585Bryan Basham – Overview of JPA v2.0 Slide 55
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Joins ● Like SQL joins; natural for relationship traversal ● Support for outer join ● Support for so-called “FETCH JOIN” which allows the query to specify a Lazy relationship to be pre-fetched.Bryan Basham – Overview of JPA v2.0 Slide 56
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Join Examples ● Get Employees for a specific project and gender: SELECT e FROM Employee AS e JOIN e.projects p WHERE p.name=:N AND e.gender=:SEX ● Get Projects with team members from a specific Department: SELECT p FROM Project p JOIN p.team emp JOIN emp.department dept WHERE dept.name=:DEPTBryan Basham – Overview of JPA v2.0 Slide 57
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy SELECT Clause ● Select Entity objects (most of what weve seen) – The result is an Entity object ● Select specific attributes (like SQL) – The result is an Object[] result ● Select aggregations (like SQL) – May use a GROUP BY clause ● May construct new Entities from a query ● May use DISTINCT; like in SQLBryan Basham – Overview of JPA v2.0 Slide 58
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Aggregation Example ● Department stats: # of Emps and youngest age private void queryEmployeeStatsByDept(Department dept) { String statement = "SELECT COUNT(e), MAX(e.dateOfBirth) FROM Employee e JOIN e.department dept WHERE dept.name=:DEPT"; Query query = em.createQuery(statement); query.setParameter("DEPT", dept.getName()); Object[] tuple = (Object[]) query.getSingleResult(); Long numOfEmps = (Long) tuple[0]; Date minDOB = (Date) tuple[1]; System.out.println(String.format("There %d employees in the %s department with the youngest age of %d years.", numOfEmps, dept.getName(), DateUtils.dateDiffYears(new Date(), minDOB))); } There 5 employees in the IT department with the youngest age of 20 years.Bryan Basham – Overview of JPA v2.0 Slide 59
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy GROUP BY Example ● List # of Emps by Department and Gender private void queryDepartmentStats() { String statement = "SELECT dept.name, emp.gender, COUNT(emp) FROM Employee emp JOIN emp.department dept GROUP BY dept.name, emp.gender"; Query query = em.createQuery(statement); List<Object[]> list = (List<Object[]>) query.getResultList(); System.out.println("Department stats:"); for ( Object[] tuple : list ) { String deptName = (String) tuple[0]; Gender gender = (Gender) tuple[1]; Long numOfEmps = (Long) tuple[2]; System.out.println("t" + deptName + " & " + gender.name() + " : " + numOfEmps + " employees"); } } Department stats: Exec & FEMALE : 1 employees Exec & MALE : 5 employees HR & FEMALE : 1 employees HR & MALE : 6 employees ... and so on ...Bryan Basham – Overview of JPA v2.0 Slide 60
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UPDATE and DELETE ● JPA also allows bulk updates and deletes ● Syntax: – UPDATE Entity AS e SET e.prop1=val1, e.prop2=val2, ... WHERE e.property = ? – DELETE FROM Entity AS e WHERE e.property = ?Bryan Basham – Overview of JPA v2.0 Slide 61
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UPDATE Example private void resetPasswordsByDept(Department dept, String newPW) { try { em.getTransaction().begin(); String statement = "UPDATE User u SET u.password=? WHERE u.employee.id IN (SELECT e.id FROM Employee e WHERE e.department=?)"; Query query = em.createQuery(statement); query.setParameter(1, newPW); query.setParameter(2, dept); int howMany = query.executeUpdate(); System.out.println(String.format("%d users passwords reset for %s", howMany, dept)); em.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); em.getTransaction().rollback(); } }Bryan Basham – Overview of JPA v2.0 Slide 62
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Containers & Deployment Relationships Keys Inheritance Beans & DB Mappings Properties Entities EntityManager CRUD Ops Entity In Practice Operations Other operations Overview of JPA v2.0 SELECT Query Parameters Containers & Query Expressions Deployment Language Joins Packaging Persistence UPDATE & SELECT Clause Unit DELETEBryan Basham – Overview of JPA v2.0 Slide 63
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Persistence Unit ● JPAs configuration – Configuration of the persistence provider, such as Hibernate – Set of entity classes; and what to exclude – Mapping configuration; if not provided by Entity class annotations ● Lives in the persistence.xml file – Typically in the META-INF directory of a JAR – Or in the WEB-INF/classes directory of a WARBryan Basham – Overview of JPA v2.0 Slide 64
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Persistence Unit (2) <?xml version="1.0" encoding="UTF-8"?> <persistence 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" version="2.0"> <persistence-unit name="unit1" transaction-type="RESOURCE_LOCAL"> <!-- details --> </persistence-unit> <persistence-unit name="unit2" transaction-type="RESOURCE_LOCAL"> <!-- details --> </persistence-unit> </persistence> // code... EntityManagerFactory emf = Persistence.createEntityManagerFactory("unit1"); EntityManager em = emf.createEntityManager(); em.persist(entity);Bryan Basham – Overview of JPA v2.0 Slide 65
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Persistence Unit (3) <persistence ...> <persistence-unit name="unit1" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>org.basham.TestJPA.mappings.Employee</class>Entity <class>org.basham.TestJPA.mappings.User</class> <class>org.basham.TestJPA.mappings.Department</class>Classes <class>org.basham.TestJPA.mappings.Project</class> <exclude-unlisted-classes /> <properties> <property name="hibernate.hbm2ddl.auto" value="create-drop" Persistence /> <property name="hibernate.show_sql" value="true" /> Provider <property name="hibernate.cache.provider_class" configuration value="org.hibernate.cache.HashtableCacheProvider" /> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:8889/TestJPA_mappings" /> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /> <property name="hibernate.connection.password" value="root" /> <property name="hibernate.connection.username" value="root" /> </properties> </persistence-unit> </persistence>Bryan Basham – Overview of JPA v2.0 Slide 66
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Packaging a Standalone App hibernate-jpa-2.0-api.jar hibernate- entitymanager- jta-1.1.jar 3.6.7-Final.jar TestJPA.jar JSR-305.jar Several other JARs .... mysql-connector- .. ..... java-5.1.5.jar .... META-INF/persistence.xmlBryan Basham – Overview of JPA v2.0 Slide 67
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Building a Standalone w/ Maven ● If you just build a standalone JAR for your app – You must include all of the external JARs by hand in the classpath during execution – Plus all of their dependencies (this gets complex) ● Or you can use Maven – To manage the transitive dependencies – And build a single executable JARBryan Basham – Overview of JPA v2.0 Slide 68
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Standalone App POM <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.basham</groupId> <artifactId>TestJPA</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <repositories> <repository> <id>repository.jboss.org</id> <name>Public JBoss Repository Group</name> <url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url> <layout>default</layout> </repository> </repositories> <!-- Build configuration and plugins --> <!-- Build dependencies --> </project>Bryan Basham – Overview of JPA v2.0 Slide 69
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Standalone App POM (2) <project ...> <!-- Build configuration and plugins --> <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>org.basham.TestJPA.app.Main</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> <!-- a few other typical Maven plugins --> </plugins> </build> </project>Bryan Basham – Overview of JPA v2.0 Slide 70
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Standalone App POM (3) <project ...> <!-- Build dependencies --> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.6.7.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.12</version> <scope>runtime</scope> </dependency> <!-- a few other dependencies --> </dependencies> </project>Bryan Basham – Overview of JPA v2.0 Slide 71
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Packing a Web App hibernate-jpa-2.0-api.jar WEB-INF/lib hibernate- entitymanager- jta-1.1.jar 3.6.7-Final.jar MyWebApp.war JSR-305.jar META-INF/ Several other JARs .... mysql-connector- .. ..... java-5.1.5.jar .... persistence.xmlBryan Basham – Overview of JPA v2.0 Slide 72
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Building a Web App ● Packing in a webapp is easier because all of the external JARs are placed in WEB-INF/lib ● Again, using Maven makes this really easyBryan Basham – Overview of JPA v2.0 Slide 73
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy In Practice Relationships Keys Inheritance Beans & DB Mappings Properties Entities Caching EntityManager CRUD Ops Locking Entity In Practice Operations Other operations Open View Overview Pattern of JPA v2.0 Partial Paging & loading Ordering SELECT Query Parameters Containers & Query Expressions Deployment Language Joins Packaging Persistence UPDATE & SELECT Clause Unit DELETEBryan Basham – Overview of JPA v2.0 Slide 74
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Paging and Ordering ● The following example demonstrates the use of paging, searching, and ordering in a real app ● This webapp, UserMgr, uses the following stack: – GWT and GXT (ExtJS widgets in GWT) – Spring – JPA and Spring DAO utilities – MySQLBryan Basham – Overview of JPA v2.0 Slide 75
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UserMgr: Users Table Ordered by Table filtered by Selected Column UserType and Last NameBryan Basham – Overview of JPA v2.0 Slide 76
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UserMgr: Users Table (2) Table supports PagingBryan Basham – Overview of JPA v2.0 Slide 77
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UserMgr: User Query Stack Server-side code «helper» JpaDaoSupport {from org.spgfrm.orm.jpa.support} «GWT» «RPC» «service» «DAO» UserGrid UserRpc UserSvc UserDao MySQL «create» «create» T=UserThe UserGrid component on the «valueObject» «valueObject»browser sends the request for anew page of Users via the GWT QueryRequest PagedQueryResultRPC async service which is notshown here. start : int totalCount : int pageSize : int items : List<T> sortField : “String” sortDir : {ASC, DESC}Bryan Basham – Overview of JPA v2.0 Slide 78
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UserMgr: UserDaoImpl public PagedQueryResult<User> retrieveUsers(final UserType userType, final QueryRequest requestInfo) { // Count the number of Users in this user type int totalCount = getJdbcTemplate().queryForInt( "SELECT count(*) FROM user WHERE user_type_id = ?", new Object[] { userType.getId() }); // Create the dynamic query (set the ORDER BY field) String sortField = requestInfo.getSortField(); Paging SortDir sortDir = requestInfo.getSortDirection(); results final String queryString = String.format( Order-by "SELECT u FROM User u" criteria + " WHERE u.userType = ? and u.deleted = false " + " ORDER BY u.%s %s", // eg) " ORDER BY u.lastName ASC" sortField, sortDir.name()); // Perform the query // SEE NEXT SLIDE return new PagedQueryResult<User>(totalCount, users); }Bryan Basham – Overview of JPA v2.0 Slide 79
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UserMgr: UserDaoImpl (2) public PagedQueryResult<User> retrieveUsers(final UserType userType, final QueryRequest requestInfo) { final String queryString = // SEE PREVIOUS SLIDE // Perform the query List<User> users = (List<User>) getJpaTemplate().executeFind( new JpaCallback() { public Object doInJpa(EntityManager em) throws PersistenceException { Paging Query query = em.createQuery(queryString); criteria query.setParameter(1, userType); query.setMaxResults(requestInfo.getPageSize()); query.setFirstResult(requestInfo.getStart()); return query.getResultList(); } }); return new PagedQueryResult<User>(totalCount, users); }Bryan Basham – Overview of JPA v2.0 Slide 80
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Partial Loading ● Associations can have a FetchType of either: – LAZY : Fetch when requested (aka “lazy loaded”) ● One-to-Many ● Many-to-Many – Or EAGER : Fetch when Entity is retrieved ● One-to-One ● Many-to-One ● Properties can also be lazy loaded – Default is eagerBryan Basham – Overview of JPA v2.0 Slide 81
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Partial Loading Poor Example 1 1..* «entity» type users «entity» UserType User @Entity @Table(name="USR_TYP") public class UserType { Whats wrong with this relationship? @Id @GeneratedValue @Column(name="SID") It depends... private Long id; @Column(name="NAME", length=32, unique=true) private String name; @OneToMany(fetch = FetchType.EAGER) private Set<User> users;Bryan Basham – Overview of JPA v2.0 Slide 82
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Partial Loading Solution ● In the situation where there could be thousands of Users per UserType: – Remove the bi-directional association – Provide a Service tier method to query the Users by type, possibly with paging and filtering 1 «entity» type «entity» UserType User «service» UserTypeService getUsers(Long typeId) : Set<User> // better yet use // paging & filteringBryan Basham – Overview of JPA v2.0 Slide 83
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Partial Loading Example @Entity @Table(name="USR") public class User { @Id @GeneratedValue @Column(name="SID") private Long id; Dont want to expose @Basic(optional = false) the users password @Column(name="NAME", length=32, unique=true) to the GUI. private String userName; @Basic(optional = false , fetch = FetchType.LAZY) @Column(name="PW", length=16) private String password; Also, the GUI rarely needs access to the @Basic(optional = false) Employee record. @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name="EMP_SID") private Employee employee;Bryan Basham – Overview of JPA v2.0 Slide 84
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Partial Loading Example (2) Typical transaction boundary «GWT» «RPC» «service» «DAO» UserGrid UserRpc UserSvc UserDao u.getEmployee().getAge() «create» «entity» «entity» User User But outside of the txn boundary The User object is “managed” access to the associated within a transactional boundary. Employee object fails: Outside that boundary the entity LazyInitializationException becomes “detached”.Bryan Basham – Overview of JPA v2.0 Slide 85
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Open Session in View Pattern ● One solution is to move the transaction boundary up the stack (say in Servlet filter): Transaction boundary «filter» «GWT» Open «RPC» «service» «DAO» UserGrid EntityManager UserRpc UserSvc UserDao InViewFilter u.getEmployee().getAge() «entity» UserBryan Basham – Overview of JPA v2.0 Slide 86
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Optimistic Locking ● Assumed, but code support must be injected ● The @Version annotation is used to flag an Entity attribute as the “version attribute” – @Version long version – @Version Date versionStamp ● An OptimisticLockException is thrown when one session attempts to update the entity after another session has already done soBryan Basham – Overview of JPA v2.0 Slide 87
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Pessimistic Locking ● Can lock an individual entity: User user = em.find(User.class, 47L); em.lock(user, LockModeType.PESSIMISTIC_WRITE); // OR simply: User user = em.find(User.class, 47L, LockModeType.PESSIMISTIC_WRITE); ● Can lock all entities returned by a query: String statement = // some limited query TypedQuery<User> query = em.createQuery(statement, User.class); query.setLockMode(LockModeType.PESSIMISTIC_READ); List<User> users = query.getResultList();Bryan Basham – Overview of JPA v2.0 Slide 88
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Caching ● The JPA spec supports the use of second-level caching by the persistence provider. ● The developer can mark Entity classes to be cached by the @Cacheable annotation. ● Similarly the developer can mark an Entity class to never be cached using: @Cacheable(false)Bryan Basham – Overview of JPA v2.0 Slide 89
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Caching Example 0..* children «entity» 0..1 Category parent @Entity @Cacheable(true) public class Category { The Category entity represents a reflexive hierarchy that rarely @Id @GeneratedValue changes; thus is a good candidate private Long id; for caching. private String title; @ManyToOne private Category parent; @Transient private Set<Category> children = new HashSet<Category>();Bryan Basham – Overview of JPA v2.0 Slide 90
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Q&A Relationships Keys Inheritance Beans & DB Mappings Properties Entities Caching EntityManager CRUD Ops Locking Entity In Practice Operations Other operations Open View Overview Pattern of JPA v2.0 Partial Paging & loading Ordering SELECT Query Parameters Containers & Query Expressions Deployment Language Joins Packaging Persistence UPDATE & SELECT Clause Unit DELETEBryan Basham – Overview of JPA v2.0 Slide 91
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Ten Great Topics Not Covered 1) Composite keys; great for mapping to an existing DB schema 2) Primary key generation; eg) hashes or UUID 3) Native SQL queries 4) GROUP BY and HAVING clauses 5) More nuances of Entity relationships 6) More nuances to DB mappings 7) Entity lifecycle events and listeners (could be used for data manipulation or auditing) 8) Bean validation 9) Programmatic query APIs 10) Metamodel APIsBryan Basham – Overview of JPA v2.0 Slide 92
    • Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Resources ● JPA v2.0 – JSR 317 (click here) – Javadocs (click here) – Tutorials (click here) ● JPA Documentation – Wikipedia (click here) – Wikibooks (click here)Bryan Basham – Overview of JPA v2.0 Slide 93