Friday, February 18, 2011

Object Relationship Mapping (ORM)


Introduction
  • Relational Database: In a relational database, data is related together from table to table via special columns called primary and foreign keys.
  • OOPs : We relate entities via references to each other through composition and aggregation.
  • Object Relational Mapping (ORM) : Defines a mapping strategy to relate Java objects to relational tables.
  • JPA : Defines relationships using fields and annotations in the entity classes. JPA mappings are established via annotations. 


Major Relationship Types Supported by JPA


1.  One-to-many

  • Relate a row in a parent table to one or more rows in a child table.
  • Relationships can either be defined as bi-directional or uni-directional.
  • Two tables are related in a one-to-many (1—M) relationship if for every row in the first table, there can be zero, one, or many rows in the second table
  • For every row in the second table there is exactly one row in the first table.
  • The one-to-many relationship is also referred to as a parent-child or master-detail relationship.
  • One-to-many relationships are the most commonly modeled relationship.
  • eg: Student and Course
    • One student can apply for one or more courses.
2.  One-to-one
  • A single row in one table is related to a single row in another table.
  • Two tables are related in a one-to-one (1—1) relationship if, for every row in the first table, there is at most one row in the second table.
  • True one-to-one relationships seldom occur in the real world. 
  • This type of relationship is often created to get around some limitation of the database management software rather than to model a real-world situation.
  • eg: Student and Address
    • One Student can have exactly one Address
3.  Many-to-Many
  • Rows from each table are related to rows in another table.
  • Two tables are related in a many-to-many (M—M) relationship when for every row in the first table, there can be many rows in the second table
  • For every row in the second table, there can be many rows in the first table.
  • Many-to-many relationships can't be directly modeled in relational database programs
  • These types of relationships must be broken into multiple one-to-many relationships
  • eg: Student and Teachers
    • One Student is taught by many Teachers and one Teacher has many Students.
4.  Many-to-One
  • A reference from a child entity back to its parent.
  • eg: Course and Student
    • Many Courses are applied by one Student.
5.  Inheritance
  • JPA supports object-based inheritence and provides several physical models to map this onto a database.


No comments:

Post a Comment