1 4 annotating persistence
TRANSCRIPT
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 1/53
Annotating Persistence
Applications
Struts University Series
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 2/53
Annotating Persistence
ApplicationsIn this session, we learn how to use
annotations to describe object
relationships and associations that theJPA cannot deduce on its own.
In the lab, we extend the User object to
include other properties, including a listof subscriptions.
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 3/53
Annotating Persistence
ApplicationsWhat are annotations?
How do we declare properties?
How do we declare relationships?
How do we declare inheritance?
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 4/53
What are annotations?
Advanced mechanisms often need
different concerns to work together
Dynamic proxy may need a paired interfaceand implementation (Web Services)
JavaBeans may need a way to override
getter/setter conventions (BeanInfo)
Serialization may not need to serialize
everything (transient)
We may need to indicate that a member is
being retired (@deprecated)
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 5/53
What are annotations?
Message Resources (*_es.properties)
Deployment descriptors (web.xml)
Workflow configuration (struts.xml)
Object validation (object-validator.xml)
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 6/53
What are annotations?
Annotations are a Java 5 mechanism for
attaching metadata (gluecode) to a
member @Annotation(name=value) member
Available to Java as XDoclet for years
Available in C# for even longer JPA is annotation-enabled XML descriptor can override annotations
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 7/53
What are the JPA Annotations?
Entity
Locking
Identity
Composition
Database Schema
Attributes
Direct Mappings
Relationship
Mappings
Queries
Entity Manager
Inheritance
Lifecycle CallBack
Events
http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-annotations.html
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 8/53
Entity / Locking
@Entity @Version
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 9/53
Identity
@Id
@IdClass
@EmbeddedId@GeneratedValue
@SequenceGenerator
@TableGenerator
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 10/53
Database Schema Attributes
@Table
@SecondaryTable
@SecondaryTables@Column
@JoinColumn
@JoinColumns
@PrimaryKeyJoinColumn
@PrimaryKeyJoinColumns
@JoinTable
@UniqueConstraint
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 11/53
Direct Mappings
@Basic
@Enumerated
@Temporal@Lob
@Transient
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 12/53
Relationship Mappings
@OneToOne
@OneToMany
@ManyToOne@ManyToMany
@MapKey
@OrderBy
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 13/53
Queries
@NamedQuery
@NamedQueries
@NamedNativeQuery@NamedNativeQueries
@QueryHint
@ColumnResult
@EntityResult
@FieldResult
@SqlResultSetMapping
@SqlResultSetMappings
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 14/53
Composition
@Embeddable
@Embedded
@AttributeOverride@AttributeOverrides
@AssociationOverride
@AssociationOverrides
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 15/53
Inheritance
@Inheritance
@DiscriminatorColumn
@DiscriminatorValue@MappedSuperclass
@AssociationOverride
@AssociationOverrides
@AttributeOverride
@AttributeOverrides
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 16/53
Lifecycle Callback Events
@PrePersist
@PostPersist
@PreRemove@PostRemove
@PreUpdate
@PostUpdate
@PostLoad
@EntityListeners@ExcludeDefaultListeners
@ExcludeSuperclassListeners
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 17/53
Entity Manager
@PersistenceUnit
@PersistenceUnits
@PersistenceContext@PersistenceContexts
@PersistenceProperty
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 18/53
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 19/53
Annotating Persistence
ApplicationsWhat are annotations?
How do we declare properties?
How do we declare relationships?
How do we declare inheritance?
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 20/53
How do we declare properties?
Entity
Table
Column
Id
GeneratedValue
Version
Basic
Transient
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 21/53
Entity
@Entity public class User implements Serializable {
@Entity is requiredMust be persisted by EntityManager
Serializable is recommended
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 22/53
Entity
@Entity(name=”USER”) public class UserImpl extends UuidEntity
implements User, Serializable {
Name attribute is used by queries (SELECT u FROM USER)Defaults to class name
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 23/53
Entity
@Entity public class User implements Serializable { @Id // field access private String id ; public String getId() { return id ; } public void setId(String value) { id = value; }}
Primary key (@Id) is required
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 24/53
Entity
@Entity public class User implements Serializable { private String id ; @Id // property access public String getId() { return id ; } public void setId(String value) { id = value; }}
Either fields or getters may be annotated But not both in the same class hierarchy!
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 25/53
Table
@Entity(name="USER")@Table(name="APP_USER")
public class UserImpl extends UuidEntity implements Serializable, User {
name, catalog, schema, uniqueConstantsWorks well with Entity to isolate per database settings
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 26/53
Column
name, unique, nullable, insertable, updatable,columnDefinition, table, length, precision, scale
// ... public class User implements Serializable { @Column(length = 64) private String from_address;public String getFromAddress()
{return from_address;} // ...}
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 27/53
Id
public class Message { @Id private Long id ;}
Use @Column to specify a different namePrimitive or wrapper type, String, Date (sql or util)
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 28/53
GeneratedValue
public class Message { @Id @GeneratedValue private Long id ;
// ...}
public class Message { @Id @GeneratedValue(GenerationType.SEQUENCE) private Long id ;
// ...
}
Used with @Id
.AUTO, IDENTITY, .SEQUENCE
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 29/53
Version
public class UuidEntity implements Serializable {
@Version private Timestamp last_update;
// ...}
int, Integer, short, Short, long, Long,Timestamp
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 30/53
Basic
Default annotation for unannotated fields or propertiesfetch, optional
FetchType = (EAGER, LAZY)
// ...@Basic(fetch=FetchType.LAZY )
private List<Subscription> subscriptions;// ...
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 31/53
Basic
Java primitive types, wrappers of the primitive types,String, BigInteger, BigDecimal, util.Date,
Calendar, sql.Date, Time, Timestamp, byte[],
Byte[], char[], Character[], enums, and any
other type that implements Serializable.
// ...@Basic(fetch=FetchType.LAZY )
private List<Subscription> subscriptions;// ...
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 32/53
Transient
@Entity public class User { @Transient private String password1 = null;// ...}
@Entity public class User implements Serializable {
private transient String password1 = null;// ...}
Transient members are not persisted
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 33/53
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 34/53
Annotating Persistence
ApplicationsWhat are annotations?
How do we declare properties?
How do we declare relationships?
How do we declare inheritance?
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 35/53
How do we declare relationships?
@OneToOne
@OneToMany
@ManyToOne
@NamedQuery
@NamedQueries
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 36/53
OneToOne
cascade, fetch, mappedBy, optional, targetEntity,
@Entity@Table(name = "APP_MESSAGE")
public class Message implements Serializable { @Id @GeneratedValue
private Long id; @OneToOne(cascade = CascadeType.ALL) private Message message;
// ...
}
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 37/53
OneToMany
cascade, fetch, mappedBy, targetEntity
// ... public class User implements Serializable {
@OneToMany(cascade = CascadeType.ALL)
private List<Subscription> subscriptions;
// ... public class UserImpl extends UuidEntity implements
@OneToMany(cascade = CascadeType.ALL, mappedBy=”user”, targetEntity=SubscriptionImpl.class) private List<Subscription> subscriptions;
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 38/53
OneToMany
@Entity(name="USER")@Table(name="APP_USER")
public class UserImpl extends UuidEntity implements
@OneToMany(cascade = CascadeType.ALL, mappedBy=”user”, targetEntity=SubscriptionImpl.class) private List<Subscription> subscriptions;
Inverse side of the relationship
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 39/53
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 40/53
What's an “owner” or “inverse”
side of a relationship?Owner “persists” the relationship To change which instances are related,
which side (table) do we change? Terminology may seem counter-intuitive
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 41/53
What's an “owner” or “inverse”
side of a relationship?In 1:M or M:1, Many is always the owner. Change the key on the many side, change
the relationship, (Can't change the One, because the the One
side is usually a primary key!)
Important because application must keep
relationships synchronized with anychanges
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 42/53
OneToMany
@Entity(name="USER")@Table(name="APP_USER")
public class UserImpl extends UuidEntity implements
@OneToMany(cascade = CascadeType.ALL, mappedBy=”user”, targetEntity=SubscriptionImpl.class) private List<Subscription> subscriptions;
Inverse side of the relationship
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 43/53
ManyToOne
// ... public class SubscriptionImpl extends UuidEntity
@JoinColumn(nullable = false) @ManyToOne(targetEntity = UserImpl.class) private User user;
Owner side of the relationship
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 44/53
NamedQuery
Name, query, queryHint[]
@Entity@NamedQuery(name = "User.COUNT",
query = "SELECT COUNT(*) FROM USER") public class User implements Serializable {
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 45/53
NamedQuery
Hints are provider-specific options or settings
cacheable, timeout, readOnly, comment
@Entity@NamedQuery(
name="findAllEmployees",query="SELECT * FROM EMPLOYEE WHERE MGR=1"
hints={@QueryHint(name=TopLinkQueryHints.REFRESH, value=HintValues.TRUE)
})
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 46/53
NamedQueries
@NamedQueries( {@NamedQuery(name = User.FIND_ALL,
query = UserImpl.FIND_ALL_QUERY ),@NamedQuery(name = User.FIND_BY_NAME ,
query = UserImpl.FIND_BY_NAME_QUERY ),@NamedQuery(name = User.COUNT ,
query = UserImpl.COUNT_QUERY )})
public class UserImpl extends UuidEntity implements
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 47/53
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 48/53
Annotating Persistence
ApplicationsWhat are annotations?
How do we declare properties?
How do we declare relationships?
How do we declare inheritance?
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 49/53
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 50/53
Annotating Persistence
ApplicationsWhat are annotations?
How do we declare properties?
How do we declare relationships?
How do we declare inheritance?
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 51/53
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 52/53
Resources
Toplink JPA Annotation Reference http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-annotations.html
/docs/jpa-docs/toplink-jpa-annotations.pdf
JPA Specification, Chapters 8 and 9 http://jcp.org/en/jsr/detail?id=220
/docs/jpa-docs/ejb3_0-fr-spec-persistence.pdf
The Java Persistence APIA Simpler Programming Model for Entity Persistence
http://java.sun.com/developer/technicalArticles/J2EE/jpa/
/docs/jpa-docs/j2ee-jpa.pdf
8/6/2019 1 4 Annotating Persistence
http://slidepdf.com/reader/full/1-4-annotating-persistence 53/53
Struts University Series