Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object-Relational Mapping. Contents  Default Mapping Rules  Elementary Mapping  Embeddables  Relationship Mapping  Inheritance Mapping.

Similar presentations


Presentation on theme: "Object-Relational Mapping. Contents  Default Mapping Rules  Elementary Mapping  Embeddables  Relationship Mapping  Inheritance Mapping."— Presentation transcript:

1 Object-Relational Mapping

2 Contents  Default Mapping Rules  Elementary Mapping  Embeddables  Relationship Mapping  Inheritance Mapping

3 1. Default Mapping Rules Unless specified differently, the container or provider will apply the default rules.  Having to supply a configuration is the exception to the rule. Default mapping rules  The entity name is mapped to a relational table name.  Attribute names are mapped to a column name.

4  JDBC rules apply for mapping Java primitives to relational data types. String → VARCHAR(255) or VARCHAR2 (Oracle) Long → BIGINT Boolean → SMALLINT Integer → INTEGER or NUMBER (Oracle) …

5 2. Elementary Mapping  Tables  Primary Keys  Attributes  Access Type  Collection of Basic Types  Map of Basic Types  Mapping with XML

6 2.1 Tables @Table To change the default values related to table. Mapping the Book entity to the T_BOOK table

7 @SecondaryTables, @SecondaryTable To spread the data across multiple tables, or secondary tables.  To distribute the data of an entity across columns in both the primary table and the secondary tables.  We use secondary tables when we have expensive attributes such as large objects (BLOBs) that we want to isolate in a different table.

8 Mapping attributes of the Address entity in three different tables

9

10 2.2 Primary Keys In relational databases, a primary key uniquely identifies each row in a table. @Id, @GeneratedValue  @Id annotates an attribute as being a unique identify. It can be one of the following types: Primary types: byte, int, short, long, char Wrapper classes of primary types: Byte, Integer, Short, Long, Char Arrays of primitive or wrapper types: int[], Integer[], … String, numbers, and dates: String, BigInteger, java.util.Date, java.sql.Date

11 @GeneratedValue  The value of the identifer can be automatically generated by the persistence provider. @GeneratedValue(strategy = GenerationType.AUTO)

12 Composite Primary Keys A single dedicated column can be designed as a primary key. However, there are some cases where a composite primary key is required.  For example, a news has content, a title, and a language code (because it can be written in several languages). The primary key of the news could be the title and the language code.

13 Primary Classes To represent a composite key, a primary class must be defined. Two available annotations for defining this class:  @EmbeddedId  @IdClass

14 Primary key classes  Must include methods: equals, hashCode  Attributes must be in the set of valid types  Must be public, implement Serializable to cross architechtural layers (e.g. they will be managed in the persistent layer and used in the presentation layer)  Must have no-arg constructor.

15 @EmbeddedId An embedded object doesn't have any identity (no primary key). Its attributes will end up as columns in the table of the entity that contains it. Two step to define primary key class using in the case of using @EmbeddedId  Define primary key class annotated by the @Embeddable annotation.  Embed the primary key class into the entity with the @EmbeddedId annotation.

16 The primary key class of the news Embed the primary key class to the News entity

17 @IdClass The primary key class is just a POJO that does not require any annotation.

18 The entity has to define the primary key class using the @IdClass annotation and annotate each key with @Id.

19 2.3 Attributes The type of a attribute can be one of:  Java primitive types ( int, double, float, etc.) and the wrapper classes ( Integer, Double, Float, etc.)  Arrays of bytes and characters ( byte[], Byte[], char[], Character[] )  String, large numeric, and temporal types (java.lang.String, java.math.BigInteger, java.math.BigDecimal, java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, java.sql.Timestamp)

20  Enumerated types and user-defined types that implement the Serializable interface  Collections of basic and embeddable types Some annotations can be used for attributes  @Basic  @Column  @Temporal  @Transient  @Enumerated

21 @Basic @Basic annotation elements @Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface Basic { FetchType fetch() default EAGER; boolean optional() default true; }  optional (true or false) : gives a hint as to whether the value of the attribute may be null (it is disregarded for primitive types).

22  fetch ( LAZY or EAGER ): gives a hint to provider runtime that data should be fetched lazily or eagerly. LAZY : the data will be fetched only when the application asks for the property. EAGER : the data is initially loaded.

23 For example, a CD album is made up of several tracks, and each track has a title, a description, and a WAV file of a certain duration that you can listen to.  The WAV file is a BLOB that can be a few megabytes long. When you access the Track entity, you don’t want to eagerly load the WAV file; you can annotate the attribute with @Basic(fetch = FetchType.LAZY) so the data will be retrieved from the database lazily (only when you access the wav attribute using its getter, for example).

24 The Track Entity The wav attribute is annotated with @Lob to store the value as a large object.

25 @Column @Column annotation elements @Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface Column { String name() default ""; boolean unique() default false; boolean nullable() default true; boolean insertable() default true; boolean updatable() default true; String columnDefinition() default ""; String table() default ""; int length() default 255; int precision() default 0; // decimal precision int scale() default 0; // decimal scale }

26

27 @Temporal In Java, you can use java.util.Date and java.util.Calendar to store data and then have several representations of it such as a date, an hour, or milliseconds. To specify this in ORM, you can use the @javax.persistence.Temporal annotation. This has three possible values: DATE, TIME, or TIMESTAMP.

28 A Customer entity has a date of birth and a technical attribute that stores the exact time it was created in the system.

29 @Transient As soon as a class is annotated with @Entity, all its attributes are automatically mapped to a table. If you do not need to map an attribute, you can use the @Transient annotation. Adding a new age attiribute to the Customer entity.  This age attribute can be automatically calculated from the date of birth.  The age attribute does not need to be mapped, and therefore can be transient.

30 As a result, the age attribute doesn’t need any AGE column to be mapped to.

31 @Enumerated Enumeration types  The values of an enum are constants and have an implicit ordinal assignment that is determined by the order in which they are declared. This ordinal cannot be modified at runtime but can be used to store the value of the enumerated type in the database.

32 Credit Card Type Enumeration public enum CreditCardType { VISA, MASTER_CARD, AMERICAN_EXPRESS } The ordinals assigned to the values of this enumerated type at compile time are  0 for VISA,  1 for MASTER_CARD, and  2 for AMERICAN_EXPRESS.

33 By default, the persistence providers will map this enumerated type to the database assuming that the column is of type Integer.  A better solution would be to store the name of the value as a string instead of storing the ordinal. The CreditCardType database column will be of type VARCHAR and a Visa card will be stored with the string "VISA".

34 2.4. Access Type Beginning Java EE6 Platform with GlashFish 3 (pages 75-79)

35 2.5. Collection of Basic Types Mapping for attributes of the following collection interfaces:  java.util.Collection  java.util.Set  java.util.List The @ElementCollection is used to indicate that an attribute of the above types.  The @ElementCollection indicates that the data of the collection is stored in a collection table. The @CollectionTable is used to customize details of the collection table such as its name.

36

37 2.6. Map of Basic Types Mapping for attributes of the interface:  java.util.Map The @ElementCollection is used to indicate that an attribute of the above types.  The @ElementCollection indicates that the data of the collection is stored in a collection table. The @CollectionTable is used to customize details of the collection table such as its name. The @MapKeyColumn is used to specified the mapping for the key column of the map.

38

39 2.7. Mapping with XML Beginning Java EE6 Platform with GlashFish 3 (pages 82-84)

40 3. Embeddables  Embeddables  Access Type of an Embeddable Class

41 3.1. Embeddables Embeddables are objects that don't have a persistent identity on their own.  They can be embedded only within owning entities.  They are stored as an intrinsic part of an owning entity and share the identity of this entity. Each attribute of the embedded object is mapped to the table of the entity. It is a strict ownership relationship (composition), so that if the entity is removed, the embedded object is also. The owning entity can have collections of embeddables as well as a single embeddable attributes.

42

43 3.2. Access Type of an Embeddable Class The access type of an embeddable class is determined by the access type of the entity class in which it exists.  For example, if the entity uses property access type, an embeddable class will implicitly use property access as well.  A different access type for an embeddable class can be specified by means of the @Access annotation.

44 Explicitly setting the access type on embeddables is strongly recommended to avoid mapping errors when an embeddable is embedded by multiple entities. The Address access type must be set explicitly.

45 4. Relationship Mapping  Relationships  Relationships in Relational Database  Entity Relationships  Fetching Relationships  Ordering Relationships

46 4.1. Relationships The world of object-oriented programming abounds with classes and relationships between classes. A relationship has a direction  Unidirectional relationship: One object can navigate toward another, but not the inverse.

47  Bidirectional relationship: One object can navigate toward another and vice versa. A relationship has a multiplicity (or cardinality)

48  In UML, a cardinality is a number or a range between a minimum and a maximum number. 0 1 n * m..n A relationship has an ownership (i.e. the owner of the relationship).  In a unidirectional relationship, ownership is implied.

49  In a bidirectional relationship, the owner has to be specified explicitly. We then show the owning side, which specifies the physical mapping, and the inverse side (the non-owning side).

50 4.2. Relationships in Relational Databases To model a relationship, we have tables. To represent a relationship between one class and another, in database we get a table reference.  Foreign key (a join column)  Join table

51 A relationship using a join column

52 A relationship using a join table

53 4.3. Entity Relationships  Cardinality Between Two Entities  @OneToOne Unidirectional  @OneToOne Bidirectional  @OneToMany Unidirectional  @ManyToOne/@OneToMany Bidirectional  @ManyToOne Unidirectional  @ManyToMany Unidirectional  @ManyToMany Bidirectional

54 4.3.1. Cardinality Between Two Entities The cardinality between two entities may be one-to-one, one-to-many, many-to-one, or many-to-many.  Each respective mapping is named after the cardinality of the source and target: @OneToOne @OneToMany @ManyToOne @ManyToMany  Each annotation can be used in a unidirectional or bidirectional way.

55  All relationships in Java and JPA are unidirectional, in that if a source object references a target object there is no guarantee that the target object also has a relationship to the source object. This is different than a relational database, in which relationships are defined through foreign keys and querying such that the inverse query always exists.

56 All possible cardinality-Direction combinations

57 4.3.2. @OneToOne Unidirectional

58 By default, the ADDRESS_ID column is nullable. A one-to-one relationship is mapped to a zero or one.

59 @JoinColumn annotation allows us to rename the foreign key column and refuse the null value.

60 4.3.3. @OneToOne Bidirectional Bidirectional relationships have an owning and an inverse side.  The inverse side of a bidirectional relationship must refer to its owning side by using the mappedBy element of the @OneToOne, @OneToMany, or @ManyToMany annotation.

61  For one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key.

62

63 4.3.4. @OneToMany Unidirectional

64

65 Changing the join table name, foreign key columns of the owning side and the inverse side.

66

67 Using foreign keys instead of join tables

68 4.3.5. ManyToOne/@OneToMany Bidirectional Each House has many Students, each Student has one House. House has a one-to- many relationship with Student, Student has a many-to-one relationship with House.  The many side of many-to-one bidirectional relationships must not define the mappedBy element. The many side is always the owning side of the relationship.

69 @OneToMany - the relation's "inverse" side @ManyToOne - the relation's "owning" side

70 4.3.6. @ManyToOne Unidirectional LineItem has a field, vendorPart, that has a unidirectional many-to-one relationship with VendorPart.

71

72 4.3.7. @ManyToMany Unidirectional It is similar to a @OneToMany unidirectional relationship. The main difference between a OneToMany and a ManyToMany relationship in JPA is that a ManyToMany always makes use of a join table to store the relationship, where as a OneToMany can either use a join table, or a foreign key in target object's table referencing the source object table's primary key.

73 A CD album is created by several artists, and an artist appears on several albums. In this example, we want to get information about the CD from an artist but not in the invserse. An artist object can navigate toward its CD album.

74

75 4.3.7. @ManyToMany Bidirectional Assuming the Artist entity is the owner of the relationship means that the CD is the reverse owner and needs to use the mappedBy element on its @ManyToMany annotation.  mappedBy tells the persistence provider that appearsOnCDs is the name of the corresponding attribute of the owning entity.

76

77 Artist, CD, and the join table

78 4.4. Fetching Relationships All the annotations ( @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany ) define a fetching attribute, specifying the associated objects to be loaded immediately (eagerly) or deferred (lazily), with a resulting impact on performance.

79 Default Fetching Strategies

80 EAGER will bring all the data into memory using a small amount of database access (the persistence provider will probably use join queries to join the tables together and extract the data). With LAZY, you don’t take the risk of filling up your memory because you control which object is loaded. But you have to access the database every time.

81 4.5. Ordering Relationships Beginning Java EE6 Platform with GlashFish 3 (pages 102-105)

82 5. Inheritance Mapping  Inheritance Strategies  Single-Table Strategy  Joined Strategy  Table-per-Class Strategy  Type of Classes in the Inheritance Hierarchy

83 5.1. Inheritance Strategies JPA 2.0 delivers declarative support for defining and mapping inheritance hierarchies, including entities, abstract entities, mapped classes, and transient classes. The @Inheritance annotation is used on the root entity to dictate the mapping strategy to itself and to the leaf classes. JPA also transposes the object notion of overriding to the mapping, which allows root class attributes be overridden by child classes.

84 JPA supports three different strategies.  A single-table-per-class hierarchy strategy: The sum of the attributes of the entire entity hierarchy is flattened down to a single table (this is the default strategy).  A joined-subclass strategy: In this approach, each entity in the hierarchy, concrete or abstract, is mapped to its own dedicated table.  A table-per-concrete-class strategy: This strategy maps each concrete entity hierarchy to its own separate table.

85 Inheritance hierarchy between CD, Book, and Item The Item entity is the root entity and has an identifier, which will turn into a primary key, from which both the CD and Book entities inherit. Each of these leaf classes adds extra attributes such as an ISBN for the Book entity or a total time duration for the CD entity.

86 5.1.1. Single-Table Strategy All the entities in the hierarchy are mapped to a single table. As it is the default, the @Inheritance annotation can be omitted on the root entity

87

88 the ITEM table sums all the attributes of the Item, Book, and CD entities. But there’s an additional column that doesn’t relate to any of the entities’ attributes: it’s the discriminator column, DTYPE.

89 The discriminator column is called DTYPE by default, is of type String (mapped to a VARCHAR), and contains the name of the entity.  If the defaults don’t suit, the @DiscriminatorColumn annotation allows you to change the name and the data type.

90 The single-table strategy is the default, is the easiest to understand, and works well when the hierarchy is relatively simple and stable. However, it has some drawbacks; adding new entities to the hierarchy, or adding attributes to existing entities, involves adding new columns to the table, migrating data, and changing indexes. This strategy also requires the columns of the child entities to be nullable. If the ISBN of the Book entity happens to be nonnull, you cannot insert a CD anymore, because the CD entity doesn’t have an ISBN.

91 5.1.2. Joined Strategy Each entity in the hierarchy is mapped to its own table. The root entity maps to a table that defines the primary key to be used by all tables in the hierarchy, as well as the discriminator column. Each subclass is represented by a separate table that contains its own attributes (not inherited from the root class) and a primary key that refers to the root table’s primary key. The nonroot tables do not hold a discriminator column.

92

93 Mapping inheritance with a joined strategy

94 The ITEM table The CD table The BOOK table

95 The joined strategy is intuitive and is close to what you know from the object inheritance mechanism. But querying can have a performance impact. If this strategy is called joined, it’s because to reassemble an instance of a subclass, the subclass table has to be joined with the root class table.  The deeper the hierarchy, the more joins needed to assemble a leaf entity.

96 5.1.3. Table-per-(Concrete) Class Strategy Each entity is mapped to its own dedicated table like the joined strategy. The difference is that all attributes of the root entity will also be mapped to columns of the child entity table. From a database point of view, this strategy denormalizes the model and causes all root entity attributes to be redefined in the tables of all leaf entities that inherit from it.

97 With the table-per-class strategy, there is no shared table, no shared columns, and no discriminator column. The only requirement is that all tables must share a common primary key that matches across all tables in the hierarchy.

98

99 The BOOK and CD tables duplicate the ID, TITLE, PRICE, and DESCRIPTION columns of the ITEM table.

100 The table-per-class strategy performs well when querying instances of one entity, as it is similar to using the single-table strategy: the query is confined to a single table. The downside is that it makes polymorphic queries across a class hierarchy more expensive than the other strategies.

101 Overriding Attributes  With the table-per-class strategy, the columns of the root class are duplicated on the leaf tables. They keep the same name. But what if a legacy database is being used and the columns have a different name?  JPA uses the @AttributeOverride annotation to override the column mapping and @AttributeOverrides to override several.

102  To rename the ID, TITLE, and DESCRIPTION columns in the BOOK tables:

103  To rename the ID, TITLE, and DESCRIPTION columns in the CD tables:

104 5.2. Type of Classes in the Inheritance Hierarchy Abstract Entity  An abstract class can also be specified as an entity.  An abstract entity differs from a concrete entity only in that it cannot be directly instantiated with the new keyword.  It provides a common data structure for its leaf entities and follows the mapping strategies.  For the persistence provider, an abstract entity is mapped as an entity. The only difference is in the Java space, not in the mapping.

105 Nonentity  Nonentities are also called transient classes, meaning they are POJOs. An entity may subclass a nonentity or may be extended by a nonentity.  Nonentities can be used to provide a common data structure to leaf entities.  The state of a nonentity superclass is not persistent because it is not managed by the persistence provider.

106 Item is a simple POJO with no @Entity The Book entity extends from a POJO The BOOK table has no attributes from Item

107 Mapped Superclass  The class is annotated with @MappedSuperclass.  To share state and behavior, as well as mapping information that entities inherit from.  Mapped superclasses are not entities. They are not managed by the persistence provider, do not have any table to be mapped to, and cannot be queried or be part of a relationship, but they may provide persistent properties to any entities that extend it.  They are similar to embeddable classes except they can be used with inheritance.

108

109 This hierarchy will be mapped into only one table. Item is not an entity and does not have any table. Attributes of Item and Book would be mapped to columns of the BOOK table, but mapped superclasses also share their mapping information.

110 Reference Antonio Goncalves, Beginning Java EE 6 Platform with GlassFish 3, Chapter 3, Apress 2009


Download ppt "Object-Relational Mapping. Contents  Default Mapping Rules  Elementary Mapping  Embeddables  Relationship Mapping  Inheritance Mapping."

Similar presentations


Ads by Google