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

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Abstract Classes and Interfaces.
Advertisements

Road Map Introduction to object oriented programming. Classes
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Databases Illuminated Chapter 7 The Object-Oriented Model.
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
DAY 15: ACCESS CHAPTER 2 Larry Reaves October 7,
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
IS-907 Java EE JPA: Simple Object-Relational Mapping.
Chapter 6 1 © Prentice Hall, 2002 The Physical Design Stage of SDLC (figures 2.4, 2.5 revisited) Project Identification and Selection Project Initiation.
OK lets start, who am I ?. Nayden Gochev (a.k.a. JOKe) Java Spring Android Hybris GWT EJB JSF RMI JAX-RS Struts JMS JPA Hibernate C# ASP.NET TestStudio.
1 Mapping Persistent Objects Entities represent data in the database, so changes to an entity bean result in changes to the database. That's ultimately.
WHAT IS A DATABASE? A DATABASE IS A COLLECTION OF DATA RELATED TO A PARTICULAR TOPIC OR PURPOSE OR TO PUT IT SIMPLY A GENERAL PURPOSE CONTAINER FOR STORING.
1 © Prentice Hall, 2002 Chapter 5: Logical Database Design and the Relational Model Modern Database Management 6 th Edition Jeffrey A. Hoffer, Mary B.
DAT602 Database Application Development Lecture 2 Review of Relational Database.
Topic : Hibernate 3:Advanced ORM Kaster Nurmukan.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Physical Database Design Purpose- translate the logical description of data into the technical specifications for storing and retrieving data Goal - create.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
The Java Persistence API ©SoftMoore ConsultingSlide 1.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Java Persistence API (JPA) Relationships. Kinds of relationships UML associations and aggregations (ER non- identifying relationships, shared semantics)
Mapping Objects ↔Relational DB. The Problem with Databases Databases store data in rows in tables, which are not like objects. We can simulate object.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Chapter 15 Abstract Classes and Interfaces.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA Chengyu Sun California State University, Los Angeles.
Hibernate Annotation 李日貴 (jini) jakarta99 AT gmail.com SoftLeader Tech. Corp. Taiwan Java Annotation Lesson 1.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
XP Chapter 1 Succeeding in Business with Microsoft Office Access 2003: A Problem-Solving Approach 1 Level 2 Objectives: Understanding and Creating Table.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Standards and Conventions
Data Integrity & Indexes / Session 1/ 1 of 37 Session 1 Module 1: Introduction to Data Integrity Module 2: Introduction to Indexes.
Database Constraints Ashima Wadhwa. Database Constraints Database constraints are restrictions on the contents of the database or on database operations.
N5 Databases Notes Information Systems Design & Development: Structures and links.
Lecture 5:Interfaces and Abstract Classes
Chapter 13 Abstract Classes and Interfaces
OpenAccess ORM Advanced Topics Kevin Babcock April 9, 2009.
CS6320 – Java Persistence API
Fundamentals of DBMS Notes-1.
Chapter VII: Arrays.
Logical Database Design and the Rational Model
Lesson # 9 HP UCMDB 8.0 Essentials
Databases Chapter 9 Asfia Rahman.
EF Relations Object Composition
Managing Tables, Data Integrity, Constraints by Adrienne Watt
Inheritance and Polymorphism
Chengyu Sun California State University, Los Angeles
Object-Oriented Databases
Week 4 Object-Oriented Programming (1): Inheritance
Chapter 13 Abstract Classes and Interfaces
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Database Applications (15-415) ORM - Part I Lecture 11, February 11, 2018 Mohammad Hammoud.
Chapter 3 Introduction to Classes, Objects Methods and Strings
MSIS 670 Object-Oriented Software Engineering
Chapter 12 Abstract Classes and Interfaces
CIS16 Application Programming with Visual Basic
Java Programming Course
Structured Types (9-12-2) Structured types allow composite attributes of E-R diagrams to be represented directly. Unnamed row types can also be used in.
Introduction to Data Structure
Chengyu Sun California State University, Los Angeles
Java Programming Language
ICT Database Lesson 2 Designing a Database.
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Chapter 13 Abstract Classes and Interfaces Part 01
eSeries Entities By Julie Ladner
Presentation transcript:

Object-Relational Mapping

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

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.

 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) …

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

2.1 To change the default values related to table. Mapping the Book entity to the T_BOOK table

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.

Mapping attributes of the Address entity in three different tables

2.2 Primary Keys In relational databases, a primary key uniquely identifies each row in 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

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

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.

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

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.

@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  Define primary key class annotated by annotation.  Embed the primary key class into the entity with annotation.

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

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

The entity has to define the primary key class using annotation and annotate each key

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)

 Enumerated types and user-defined types that implement the Serializable interface  Collections of basic and embeddable types Some annotations can be used for attributes

annotation 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).

 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.

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 = FetchType.LAZY) so the data will be retrieved from the database lazily (only when you access the wav attribute using its getter, for example).

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

annotation 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 }

@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 annotation. This has three possible values: DATE, TIME, or TIMESTAMP.

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

@Transient As soon as a class is annotated all its attributes are automatically mapped to a table. If you do not need to map an attribute, you can use 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.

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

@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.

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.

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".

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

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

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

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

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

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.

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 annotation.

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.

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

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.

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

 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.

 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).

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

A relationship using a join column

A relationship using a join table

4.3. Entity Relationships  Cardinality Between Two Entities Unidirectional Bidirectional Unidirectional  Bidirectional Unidirectional Unidirectional Bidirectional

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  Each annotation can be used in a unidirectional or bidirectional way.

 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.

All possible cardinality-Direction combinations

Unidirectional

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

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

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 annotation.

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

Unidirectional

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

Using foreign keys instead of join tables

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.

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

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

Unidirectional It is similar to 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.

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.

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 annotation.  mappedBy tells the persistence provider that appearsOnCDs is the name of the corresponding attribute of the owning entity.

Artist, CD, and the join table

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

Default Fetching Strategies

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.

4.5. Ordering Relationships Beginning Java EE6 Platform with GlashFish 3 (pages )

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

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. 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.

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.

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.

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

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.

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, annotation allows you to change the name and the data type.

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.

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.

Mapping inheritance with a joined strategy

The ITEM table The CD table The BOOK table

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.

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.

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.

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

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.

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 annotation to override the column mapping to override several.

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

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

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.

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.

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

Mapped Superclass  The class is annotated  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.

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.

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