0% found this document useful (0 votes)
73 views53 pages

1 4 Annotating Persistence

This document discusses how to use annotations to describe object relationships and associations in JPA applications. It begins by explaining what annotations are and how they are used to declare properties like primary keys, relationships, and inheritance. It then provides examples of common JPA annotations like @Entity, @Id, @OneToMany, @ManyToOne, and @NamedQuery and how they are used to define entities, properties, and relationships. Resources for further information on JPA annotations are also listed.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views53 pages

1 4 Annotating Persistence

This document discusses how to use annotations to describe object relationships and associations in JPA applications. It begins by explaining what annotations are and how they are used to declare properties like primary keys, relationships, and inheritance. It then provides examples of common JPA annotations like @Entity, @Id, @OneToMany, @ManyToOne, and @NamedQuery and how they are used to define entities, properties, and relationships. Resources for further information on JPA annotations are also listed.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Annotating Persistence Applications

Struts University Series

Annotating Persistence Applications


In this session, we learn how to use annotations to describe object relationships and associations that the JPA cannot deduce on its own. In the lab, we extend the User object to include other properties, including a list of subscriptions.

Annotating Persistence Applications


What are annotations? How do we declare properties? How do we declare relationships? How do we declare inheritance?

What are annotations?


Advanced mechanisms often need different concerns to work together

Dynamic proxy may need a paired interface and 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)

What are annotations?


Message Resources (*_es.properties) Deployment descriptors (web.xml) Workflow configuration (struts.xml) Object validation (object-validator.xml)

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

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

Entity / Locking
@Entity @Version

Identity
@Id @IdClass @EmbeddedId @GeneratedValue @SequenceGenerator @TableGenerator

Database Schema Attributes


@Table @SecondaryTable @SecondaryTables @Column @JoinColumn @JoinColumns @PrimaryKeyJoinColumn @PrimaryKeyJoinColumns @JoinTable @UniqueConstraint

Direct Mappings
@Basic @Enumerated @Temporal @Lob @Transient

Relationship Mappings
@OneToOne @OneToMany @ManyToOne @ManyToMany @MapKey @OrderBy

Queries
@NamedQuery @NamedQueries @NamedNativeQuery @NamedNativeQueries @QueryHint @ColumnResult @EntityResult @FieldResult @SqlResultSetMapping @SqlResultSetMappings

Composition
@Embeddable @Embedded @AttributeOverride @AttributeOverrides @AssociationOverride @AssociationOverrides

Inheritance
@Inheritance @DiscriminatorColumn @DiscriminatorValue @MappedSuperclass @AssociationOverride @AssociationOverrides @AttributeOverride @AttributeOverrides

Lifecycle Callback Events


@PrePersist @PostPersist @PreRemove @PostRemove @PreUpdate @PostUpdate @PostLoad @EntityListeners @ExcludeDefaultListeners @ExcludeSuperclassListeners

Entity Manager
@PersistenceUnit @PersistenceUnits @PersistenceContext @PersistenceContexts @PersistenceProperty

Annotating Persistence Applications


What are annotations? How do we declare properties? How do we declare relationships? How do we declare inheritance?

How do we declare properties?


Entity Table Column Id GeneratedValue Version Basic Transient

Entity
@Entity public class User implements Serializable {

@Entity is required Must be persisted by EntityManager Serializable is recommended

Entity
@Entity(name=USER) public class UserImpl extends UuidEntity implements User, Serializable {

Name attribute is used by queries (SELECT Defaults to class name

u FROM USER)

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

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!

Table
@Entity(name="USER") @Table(name="APP_USER") public class UserImpl extends UuidEntity implements Serializable, User {

name, catalog, schema, uniqueConstants Works well with Entity to isolate per database settings

Column
// ... public class User implements Serializable { @Column(length = 64) private String from_address; public String getFromAddress() {return from_address;} // ... }

name, unique, nullable, insertable, updatable, columnDefinition, table, length, precision, scale

Id
public class Message { @Id private Long id; }

Use @Column to specify a different name Primitive or wrapper type, String, Date (sql or util)

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

Version
public class UuidEntity implements Serializable { @Version private Timestamp last_update; // ... }

int, Integer, short, Short, long, Long, Timestamp

Basic
// ... @Basic(fetch=FetchType.LAZY) private List<Subscription> subscriptions; // ...

Default annotation for unannotated fields or properties fetch, optional FetchType = (EAGER, LAZY)

Basic
// ... @Basic(fetch=FetchType.LAZY) private List<Subscription> subscriptions; // ...

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.

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

Annotating Persistence Applications


What are annotations? How do we declare properties? How do we declare relationships? How do we declare inheritance?

How do we declare relationships?


@OneToOne @OneToMany @ManyToOne @NamedQuery @NamedQueries

OneToOne
@Entity @Table(name = "APP_MESSAGE") public class Message implements Serializable { @Id @GeneratedValue private Long id; @OneToOne(cascade = CascadeType.ALL) private Message message; // ... }

cascade, fetch, mappedBy, optional, targetEntity,

OneToMany
// ... 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;

cascade, fetch, mappedBy, targetEntity

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

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

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 any changes

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

ManyToOne

// ... public class SubscriptionImpl extends UuidEntity @JoinColumn(nullable = false) @ManyToOne(targetEntity = UserImpl.class) private User user;

Owner side of the relationship

NamedQuery
@Entity @NamedQuery(name = "User.COUNT", query = "SELECT COUNT(*) FROM USER") public class User implements Serializable {

Name, query, queryHint[]

NamedQuery
@Entity @NamedQuery( name="findAllEmployees", query="SELECT * FROM EMPLOYEE WHERE MGR=1" hints={ @QueryHint(name=TopLinkQueryHints.REFRESH, value=HintValues.TRUE) } )

Hints are provider-specific options or settings

cacheable, timeout, readOnly, comment

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

Annotating Persistence Applications


What are annotations? How do we declare properties? How do we declare relationships? How do we declare inheritance?

Annotating Persistence Applications


What are annotations? How do we declare properties? How do we declare relationships? How do we declare inheritance?

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 API


A Simpler Programming Model for Entity Persistence

http://java.sun.com/developer/technicalArticles/J2EE/jpa/ /docs/jpa-docs/j2ee-jpa.pdf

Struts University Series

You might also like