SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Downloaden Sie, um offline zu lesen
Persistence
                      1
By: Abdalla Mahmoud



Contents
            Persistence ......................................................................................... 1
             Contents ........................................................................................... 1
             1. Introduction ................................................................................... 0
               1.1. The Need for Business Modeling .................................................. 3
               1.2. The Need for Persistence ............................................................ 5
             2. Object-to-Relational Mapping (ORM).................................................. 6
               2.1. Entity Beans ............................................................................. 6
               2.2. Entity Manager ......................................................................... 7
               2.3. Example................................................................................... 7
                 2.3.1. Configuring a Data Source .................................................... 7
                 2.3.2. Configuring a Persistence Unit ............................................... 7
                 2.3.3. Developing the Entity class ................................................... 7
                 2.3.4. Developing the Session Bean................................................. 8
                 2.3.5. Packaging the EJB Module ..................................................... 9
             3. EntityManager ............................................................................... 10
               3.1. Persisting an Entity................................................................... 10
               3.2. Retrieving an Entity .................................................................. 10
               3.3. Deleting an Entity..................................................................... 10
               3.4. Merging an Entity ..................................................................... 10
             4. Schema Mappings .......................................................................... 10
               4.1. Basic Elementary Mappings .......................................................11
                 4.1.1. Table Mapping .................................................................... 11
                 4.1.2. Column Mapping................................................................. 11
                 4.1.3. Primary Key Mapping .......................................................... 12
               4.2. Entity Relationships Mappings ....................................................12
                 4.2.1. OneToOne ......................................................................... 12
                 4.2.2. OneToMany........................................................................ 14
                 4.2.3. ManyToMany ...................................................................... 14




1. http://www.abdallamahmoud.com



                                                     1
2
1. Introduction
   Persistence is making state outlives execution. It's a primary requirement in any enterprise
software. There's enormous amount of data that should be persisted and used for long years
even if the system went down dozens of times. Typically, data is persisted in relational
databases. As in Java SE, we used JDBC to manipulate relational database management
systems. Although JDBC is a full-features API, it's not usable in the case of development
enterprise software. To discuss that, we need to discuss two points: the need for business
modeling, and the need for persistence, in enterprise software.

1.1. The Need for Business Modeling

Enterprises are usually object-oriented analysed and designed before implemented. In most
software engineering approaches, we use domain object models for representing entities and
their relationships.
       Domain
       The context of the business itself. For example, the domain maybe HiQ Academy's
       business entities and structure. Entities include tangible and intangible real-world
       objects like a manger, an instructor, a student, a running course, etc. Relationships
       include students participating to a course, instructors teaching the course, etc.

       Model
       A representation.

       Object Model
       Object representation.

       Domain Object Model
       An object representation of the business model.
A domain object model makes the implementation of the system simpler and talkative.
Suppose the Following Object Model for a training course.




In java, we would implement the model as the following:




                                              3
file: modelCourse.java
package model ;

import java.util.ArrayList ;
import java.util.Date ;

public class Course {

    //private member variables
    private String id ;
    private String name ;
    private Date startDate ;
    private Date endDate ;
    private Instructor instructor ;
    private ArrayList<Student> students = new ArrayList<Student>() ;

    //setter and getter methods for all variables
    ...

    public void setName(String name) {this.name = name ;}
    public String getName() {return name ;}

    public void setStartDate(Date date) { ... }
    public Date getStartDate() { ... }

    ...

    //this is called ENCAPSULATION


}


file: modelInstructor.java
package model ;

public class Instructor {

    private int id ;
    private String name ;
    private String profession ;

    //setter and getter methods as shown earlier
    ...

}




                                     4
file: modelStudent.java
package model;

public class Student {

      private   int id ;
      private   String name ;
      private   int age ;
      private   String phone ;

      //setter and getter methods as shown earlier
      ...

}

      • Activity: How to automatically generate them with Netbeans IDE?

If the system is modeled like this, business logic can be implemented easily in a talkative
manner. As shown in the following business related functions written casually:

Business Related Functions
...
public void participateStudent(Student student, Course course) {
    course.getStudents().add(student) ;
}

public void participateInstructor(Instructor instructor, Course course) {
    course.setInstructor(instructor) ;
}

public void registerMySelf() {

      Instructor me = new Instructor() ;
      me.setName("abdalla mahmoud") ;
      me.setProfession("java") ;

      //javaCourse is an instance of Course representing our course
      participateInstructor(me, javaCourse) ;

}
...



1.2. The Need for Persistence

Using objects for representing the state of the enterprise is a good idea for simplifying
business logic programming, but objects are not durable as they are killed when the system




                                            5
shutdowns. Objects should be persisted in a database for two main reasons. First, if the
system crashes, objects can be built again. Second, memory is too limited to hold enterprise
data. In other words, objects should be synchronized with a database. Any changes made to
the state of the objects should be reflected to the database. This problem is called mapping
and discussed soon.


2. Object-to-Relational Mapping (ORM)
  Object-to-relational mapping is the problem of mapping objects and their attributes in
memory to tables and columns in a relational database.




     •   Every class is mapped to a table.
     •   Every attribute is mapped to column.
     •   Every object should be mapped to a row.
     •   State should be synchronized with the row.

Java Persistence API (JPA) provides a complete framework for mapping POJOs to relational
databases. It works over JDBC API and provides an interface for a virtual object-oriented
database, that's actually mapped to a relational database. The application server provides an
implementation to the Java Persistence API to the components that integrates them with the
relational database. The service synchronizes a set of entity beans and provided through the
entity manager interface.

2.1. Entity Beans

Entity beans are POJOs whose properties are encapsulated as shown earlier with setter and
getter methods. Entity beans are instances of entity classes. Entity classes are annotated
with @Entity.




                                             6
2.2. Entity Manager

The entity manager is the provider to the persistence service. It's a java interface that can be
in injected to an implementation by the application server. Persistence service is configured
using XML as persistence units and used by business components through dependency
injection.

2.3. Example

2.3.1. Configuring a Data Source

     • Copy postgresql-8.3-604.jdbc4.jar (PostgreSQL JDBC Driver) to
       C:jbossserverdefaultlib
     • Copy C:jbossdocsexamplesjcapostgres-ds.xml
       to C:jbossserverdefaultdeploypostgres-ds.xml
     • Edit postgres-ds.xml: JDBC URL, username, and password of database
       connection with PostgreSQL.
     • Run JBoss Application Server.
     • A JDBC connection is bound to the JNDI with name (java:PostgresDS).

2.3.2. Configuring a Persistence Unit

     • Every EJB module (.jar) may contain a configuration file for persistence service.
     • File should be located in JAR_ROOTMETA-INFpersistence.xml
     • This is an example for the persistence configuration file:

file: META-INFpersistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="FooPU" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>java:PostgresDS</jta-data-source>
    <properties>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
 <property name="hibernate.dialect"
value="org.hibernate.dialect.PostgreSQLDialect"/>
    </properties>
  </persistence-unit>
</persistence>



2.3.3. Developing the Entity class


file: modelInstructor.java
package ent ;




                                               7
import javax.persistence.* ;

/*
This is the entity class of the Instructor table
*/

@Entity
public class Instructor {

    @Id @GeneratedValue
    private int id ;
    private String name ;
    private String profession ;

    //setter and getter methods as shown earlier
    ...

}


2.3.4. Developing the Session Bean


file: entFooEJB.java
package ent ;

import javax.ejb.Stateless ;
import javax.persistence.* ;

/*
This is the business component that will use the persistence service
*/

@Stateless
public class FooEJB implements FooEJBRemote {

    @PersistenceContext(unitName="FooPU") EntityManager em ;

    public void foo() {

         Instructor bean = new Instructor() ;

         bean.setName("Abdalla Mahmoud") ;
         bean.setProfession("java") ;

         em.persist(bean) ;




                                      8
}

}


2.3.5. Packaging the EJB Module

     • Create the folder META-INF in the C:workspace directory.
     • Create the persistence.xml file in the C:workspaceMETA-INF directory.
     • Compile and Package the EJB module as follows:

Command Prompt
C:workspace>javac entpack*.java
C:workspace>jar cf module.jar entpack*.class META-INFpersistence.xml

Here's the final directory structure of module.jar:




                                                9
3. EntityManager

3.1. Persisting an Entity

Persisting an entity makes it managed by the entity manager and changes are synchronized
with the database.
Example
//entity is a reference to the entity
em.persist(entity) ;



3.2. Retrieving an Entity

Retrieving an entity is getting reference to it and makes it managed by the entity manager.
Example
//entity is a reference to the entity
Instructor instructor = em.find(Instructor.class, primaryKey) ;



3.3. Deleting an Entity

Removing an entity is deleting it from the database.

Example
//entity is a reference to the entity
em.remove(entity) ;



3.4. Merging an Entity

Merging an entity is making the entity managed by the entity manager the same as the
given entity.
Example
//anotherEntity is a reference to another entity with other attributes
em.merge(anotherEntity) ;



4. Schema Mappings

By default, the entity manager maps tables and columns to the same name and types found
in entity classes and attributes. For example, the earlier example is mapped to the following
table:

          ID:Serial                   name:VARCHAR                profession:VARCHAR




                                             10
Table: Instructor

Some modifications or additions to the mapping may be needed in different circumstances.
Mappings are annotated to the entity class and implemented by the entity manager. Here we
will see some mappings provided by the JPA.

4.1. Basic Elementary Mappings

4.1.1. Table Mapping

By default, entities are mapped to tables of the same name with its entity class. To modify
the name, the entity is annotated with @Table and name is specified as follows:


file: entInstructor.java

package ent ;


import javax.persistence.* ;


@Entity
@Table(name="HIQ_INSTRUCTORS")
public class Instructor {


     @Id @GeneratedValue
     private int id ;
     private String name ;
     private String profession ;


     //setter and getter methods as shown earlier
     ...


}


4.1.2. Column Mapping

By default, entity variables are mapped to column of the same name with the variables. To
modify the name, the variable is annotated with @Column and name is specified as follows:


file: entInstructor.java

package ent ;


import javax.persistence.* ;




                                             11
@Entity
@Table(name="HIQ_INSTRUCTORS")
public class Instructor {


     @Id @GeneratedValue
     private int id ;
     @Column(name="INSTRUCTOR_NAME")
     private String name ;
     private String profession ;


     //setter and getter methods
     ...


}


Other attributes can be set to @Column:

           Attribute                      Purpose                  Default Value
columnDefinition               Exact DDL type.             ""
length                         length of VARCHAR fields.   255
nullable                       Can be null.                true
unique                         Should be unique.           false


4.1.3. Primary Key Mapping

Primary key attribute is mapped using @Id as shown earlier. @GeneratedValue makes the
value of the primary key increases automatically.

4.2. Entity Relationships Mappings

4.2.1. OneToOne

One-to-one relationship is mapped using @OneToOne. Example:


file: entCourse.java

package ent ;

import java.util.ArrayList ;
import java.util.Date ;
import javax.persistence.* ;



                                              12
@Entity
public class Course {

     @Id @GeneratedValue
     private String id ;
     private String name ;
     private Date startDate ;
     private Date endDate ;
     @OneToOne(cascade={CascadeType.ALL})
     private Instructor instructor ;
     private ArrayList<Student> students = new ArrayList<Student>() ;

     //setter and getter methods
     ...

}

This is called unidirectional relationship, because only the Course refers to the Instructor. To
make Instructor also referes to both, i.e. bidirectional, we can edit the Instructor class as
follows:

file: entInstructor.java

package ent ;


import javax.persistence.* ;


@Entity
@Table(name="HIQ_INSTRUCTORS")
public class Instructor {


     @Id @GeneratedValue
     private int id ;
     @Column(name="INSTRUCTOR_NAME")
     private String name ;
     private String profession ;
     @OneToOne(mappedBy="instructor")
     private Course course ;


     //setter and getter methods
     ...




                                              13
}




4.2.2. OneToMany

One-to-many relationship is mapped using @OneToMany. Example:


file: entCourse.java

package ent ;

import java.util.ArrayList ;
import java.util.Date ;
import javax.persistence.* ;

@Entity
public class Course {

     @Id @GeneratedValue
     private String id ;
     private String name ;
     private Date startDate ;
     private Date endDate ;
     @OneToOne(cascade={CascadeType.ALL})
     private Instructor instructor ;
     @OneToMany(cascade={CascadeType.ALL})
     private ArrayList<Student> students = new ArrayList<Student>() ;

     //setter and getter methods
     ...

}

This is a unidirectional relationship. Bidirectional relationship can be implemented as shown
earlier, but using @ManyToOne relationship instead.

4.2.3. ManyToMany

Many-to-many relationship is mapped using @ManyToMany.




                                             14

Weitere ähnliche Inhalte

Was ist angesagt?

Documentation - Element and ElementVector
Documentation - Element and ElementVectorDocumentation - Element and ElementVector
Documentation - Element and ElementVectorMichel Alves
 
Applied Software Engineering Assignment
Applied Software Engineering AssignmentApplied Software Engineering Assignment
Applied Software Engineering Assignmenttdsrogers
 
Message Driven Beans (6)
Message Driven Beans (6)Message Driven Beans (6)
Message Driven Beans (6)Abdalla Mahmoud
 
FRG_P4_Final_Project_Report_Modifications_to_edX_platform
FRG_P4_Final_Project_Report_Modifications_to_edX_platformFRG_P4_Final_Project_Report_Modifications_to_edX_platform
FRG_P4_Final_Project_Report_Modifications_to_edX_platformPushkar Narayan
 
Arules_TM_Rpart_Markdown
Arules_TM_Rpart_MarkdownArules_TM_Rpart_Markdown
Arules_TM_Rpart_MarkdownAdrian Cuyugan
 
ActiveMQ Configuration
ActiveMQ ConfigurationActiveMQ Configuration
ActiveMQ ConfigurationAshish Mishra
 
Osb developer's guide
Osb developer's guideOsb developer's guide
Osb developer's guideHarish B
 
Replication in PostgreSQL tutorial given in Postgres Conference 2019
Replication in PostgreSQL tutorial given in Postgres Conference 2019Replication in PostgreSQL tutorial given in Postgres Conference 2019
Replication in PostgreSQL tutorial given in Postgres Conference 2019Abbas Butt
 
The Shortcut Guide to SQL Server Infrastructure Optimization
The Shortcut Guide to SQL Server Infrastructure OptimizationThe Shortcut Guide to SQL Server Infrastructure Optimization
The Shortcut Guide to SQL Server Infrastructure Optimizationwebhostingguy
 

Was ist angesagt? (11)

Cimplementation
CimplementationCimplementation
Cimplementation
 
Documentation - Element and ElementVector
Documentation - Element and ElementVectorDocumentation - Element and ElementVector
Documentation - Element and ElementVector
 
Applied Software Engineering Assignment
Applied Software Engineering AssignmentApplied Software Engineering Assignment
Applied Software Engineering Assignment
 
Message Driven Beans (6)
Message Driven Beans (6)Message Driven Beans (6)
Message Driven Beans (6)
 
FRG_P4_Final_Project_Report_Modifications_to_edX_platform
FRG_P4_Final_Project_Report_Modifications_to_edX_platformFRG_P4_Final_Project_Report_Modifications_to_edX_platform
FRG_P4_Final_Project_Report_Modifications_to_edX_platform
 
Arules_TM_Rpart_Markdown
Arules_TM_Rpart_MarkdownArules_TM_Rpart_Markdown
Arules_TM_Rpart_Markdown
 
ActiveMQ Configuration
ActiveMQ ConfigurationActiveMQ Configuration
ActiveMQ Configuration
 
Product Number: 0
Product Number: 0Product Number: 0
Product Number: 0
 
Osb developer's guide
Osb developer's guideOsb developer's guide
Osb developer's guide
 
Replication in PostgreSQL tutorial given in Postgres Conference 2019
Replication in PostgreSQL tutorial given in Postgres Conference 2019Replication in PostgreSQL tutorial given in Postgres Conference 2019
Replication in PostgreSQL tutorial given in Postgres Conference 2019
 
The Shortcut Guide to SQL Server Infrastructure Optimization
The Shortcut Guide to SQL Server Infrastructure OptimizationThe Shortcut Guide to SQL Server Infrastructure Optimization
The Shortcut Guide to SQL Server Infrastructure Optimization
 

Ähnlich wie Persistence ORM Mapping Explained

Spring data-keyvalue-reference
Spring data-keyvalue-referenceSpring data-keyvalue-reference
Spring data-keyvalue-referencedragos142000
 
Design patterns by example
Design patterns by exampleDesign patterns by example
Design patterns by exampleEric jack
 
An Analysis of Component-based Software Development -Maximize the reuse of ex...
An Analysis of Component-based Software Development -Maximize the reuse of ex...An Analysis of Component-based Software Development -Maximize the reuse of ex...
An Analysis of Component-based Software Development -Maximize the reuse of ex...Mohammad Salah uddin
 
Ibm urban code_deploy_v6_lab-workbook
Ibm urban code_deploy_v6_lab-workbookIbm urban code_deploy_v6_lab-workbook
Ibm urban code_deploy_v6_lab-workbookBalipalliGayathri
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionSyed Zaid Irshad
 
[Evaldas Taroza - Master thesis] Schema Matching and Automatic Web Data Extra...
[Evaldas Taroza - Master thesis] Schema Matching and Automatic Web Data Extra...[Evaldas Taroza - Master thesis] Schema Matching and Automatic Web Data Extra...
[Evaldas Taroza - Master thesis] Schema Matching and Automatic Web Data Extra...Evaldas Taroza
 
Sel dotnet documentation
Sel dotnet documentationSel dotnet documentation
Sel dotnet documentationTrương Nhiên
 
Odi best-practice-data-warehouse-168255
Odi best-practice-data-warehouse-168255Odi best-practice-data-warehouse-168255
Odi best-practice-data-warehouse-168255nm2013
 
Gym Management System User Manual
Gym Management System User ManualGym Management System User Manual
Gym Management System User ManualDavid O' Connor
 
Dissertation_of_Pieter_van_Zyl_2_March_2010
Dissertation_of_Pieter_van_Zyl_2_March_2010Dissertation_of_Pieter_van_Zyl_2_March_2010
Dissertation_of_Pieter_van_Zyl_2_March_2010Pieter Van Zyl
 
Postgres plus cloud_database_getting_started_guide
Postgres plus cloud_database_getting_started_guidePostgres plus cloud_database_getting_started_guide
Postgres plus cloud_database_getting_started_guideice1oog
 
Access tutorial
Access tutorialAccess tutorial
Access tutorialAjoenk8
 
Access tutorial (1)
Access tutorial (1)Access tutorial (1)
Access tutorial (1)yersyorrego
 

Ähnlich wie Persistence ORM Mapping Explained (20)

Spring data-keyvalue-reference
Spring data-keyvalue-referenceSpring data-keyvalue-reference
Spring data-keyvalue-reference
 
Java EE Services
Java EE ServicesJava EE Services
Java EE Services
 
Design patterns by example
Design patterns by exampleDesign patterns by example
Design patterns by example
 
An Analysis of Component-based Software Development -Maximize the reuse of ex...
An Analysis of Component-based Software Development -Maximize the reuse of ex...An Analysis of Component-based Software Development -Maximize the reuse of ex...
An Analysis of Component-based Software Development -Maximize the reuse of ex...
 
Servlets
ServletsServlets
Servlets
 
tutorialSCE
tutorialSCEtutorialSCE
tutorialSCE
 
Ibm urban code_deploy_v6_lab-workbook
Ibm urban code_deploy_v6_lab-workbookIbm urban code_deploy_v6_lab-workbook
Ibm urban code_deploy_v6_lab-workbook
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
 
[Evaldas Taroza - Master thesis] Schema Matching and Automatic Web Data Extra...
[Evaldas Taroza - Master thesis] Schema Matching and Automatic Web Data Extra...[Evaldas Taroza - Master thesis] Schema Matching and Automatic Web Data Extra...
[Evaldas Taroza - Master thesis] Schema Matching and Automatic Web Data Extra...
 
Sel dotnet documentation
Sel dotnet documentationSel dotnet documentation
Sel dotnet documentation
 
Odi best-practice-data-warehouse-168255
Odi best-practice-data-warehouse-168255Odi best-practice-data-warehouse-168255
Odi best-practice-data-warehouse-168255
 
Gym Management System User Manual
Gym Management System User ManualGym Management System User Manual
Gym Management System User Manual
 
Dissertation_of_Pieter_van_Zyl_2_March_2010
Dissertation_of_Pieter_van_Zyl_2_March_2010Dissertation_of_Pieter_van_Zyl_2_March_2010
Dissertation_of_Pieter_van_Zyl_2_March_2010
 
Eple thesis
Eple thesisEple thesis
Eple thesis
 
Postgres plus cloud_database_getting_started_guide
Postgres plus cloud_database_getting_started_guidePostgres plus cloud_database_getting_started_guide
Postgres plus cloud_database_getting_started_guide
 
Hung_thesis
Hung_thesisHung_thesis
Hung_thesis
 
Access tutorial
Access tutorialAccess tutorial
Access tutorial
 
Access tutorial
Access tutorialAccess tutorial
Access tutorial
 
Access tutorial (1)
Access tutorial (1)Access tutorial (1)
Access tutorial (1)
 
Access tutorial
Access tutorialAccess tutorial
Access tutorial
 

Mehr von Abdalla Mahmoud

Introduction to the World Wide Web
Introduction to the World Wide WebIntroduction to the World Wide Web
Introduction to the World Wide WebAbdalla Mahmoud
 
Introduction to Java Enterprise Edition
Introduction to Java Enterprise EditionIntroduction to Java Enterprise Edition
Introduction to Java Enterprise EditionAbdalla Mahmoud
 
Object-Oriented Concepts
Object-Oriented ConceptsObject-Oriented Concepts
Object-Oriented ConceptsAbdalla Mahmoud
 

Mehr von Abdalla Mahmoud (6)

JavaServer Pages
JavaServer PagesJavaServer Pages
JavaServer Pages
 
Introduction to the World Wide Web
Introduction to the World Wide WebIntroduction to the World Wide Web
Introduction to the World Wide Web
 
Introduction to Java Enterprise Edition
Introduction to Java Enterprise EditionIntroduction to Java Enterprise Edition
Introduction to Java Enterprise Edition
 
Object-Oriented Concepts
Object-Oriented ConceptsObject-Oriented Concepts
Object-Oriented Concepts
 
One-Hour Java Talk
One-Hour Java TalkOne-Hour Java Talk
One-Hour Java Talk
 
Being Professional
Being ProfessionalBeing Professional
Being Professional
 

Kürzlich hochgeladen

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Kürzlich hochgeladen (20)

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

Persistence ORM Mapping Explained

  • 1. Persistence 1 By: Abdalla Mahmoud Contents Persistence ......................................................................................... 1 Contents ........................................................................................... 1 1. Introduction ................................................................................... 0 1.1. The Need for Business Modeling .................................................. 3 1.2. The Need for Persistence ............................................................ 5 2. Object-to-Relational Mapping (ORM).................................................. 6 2.1. Entity Beans ............................................................................. 6 2.2. Entity Manager ......................................................................... 7 2.3. Example................................................................................... 7 2.3.1. Configuring a Data Source .................................................... 7 2.3.2. Configuring a Persistence Unit ............................................... 7 2.3.3. Developing the Entity class ................................................... 7 2.3.4. Developing the Session Bean................................................. 8 2.3.5. Packaging the EJB Module ..................................................... 9 3. EntityManager ............................................................................... 10 3.1. Persisting an Entity................................................................... 10 3.2. Retrieving an Entity .................................................................. 10 3.3. Deleting an Entity..................................................................... 10 3.4. Merging an Entity ..................................................................... 10 4. Schema Mappings .......................................................................... 10 4.1. Basic Elementary Mappings .......................................................11 4.1.1. Table Mapping .................................................................... 11 4.1.2. Column Mapping................................................................. 11 4.1.3. Primary Key Mapping .......................................................... 12 4.2. Entity Relationships Mappings ....................................................12 4.2.1. OneToOne ......................................................................... 12 4.2.2. OneToMany........................................................................ 14 4.2.3. ManyToMany ...................................................................... 14 1. http://www.abdallamahmoud.com 1
  • 2. 2
  • 3. 1. Introduction Persistence is making state outlives execution. It's a primary requirement in any enterprise software. There's enormous amount of data that should be persisted and used for long years even if the system went down dozens of times. Typically, data is persisted in relational databases. As in Java SE, we used JDBC to manipulate relational database management systems. Although JDBC is a full-features API, it's not usable in the case of development enterprise software. To discuss that, we need to discuss two points: the need for business modeling, and the need for persistence, in enterprise software. 1.1. The Need for Business Modeling Enterprises are usually object-oriented analysed and designed before implemented. In most software engineering approaches, we use domain object models for representing entities and their relationships. Domain The context of the business itself. For example, the domain maybe HiQ Academy's business entities and structure. Entities include tangible and intangible real-world objects like a manger, an instructor, a student, a running course, etc. Relationships include students participating to a course, instructors teaching the course, etc. Model A representation. Object Model Object representation. Domain Object Model An object representation of the business model. A domain object model makes the implementation of the system simpler and talkative. Suppose the Following Object Model for a training course. In java, we would implement the model as the following: 3
  • 4. file: modelCourse.java package model ; import java.util.ArrayList ; import java.util.Date ; public class Course { //private member variables private String id ; private String name ; private Date startDate ; private Date endDate ; private Instructor instructor ; private ArrayList<Student> students = new ArrayList<Student>() ; //setter and getter methods for all variables ... public void setName(String name) {this.name = name ;} public String getName() {return name ;} public void setStartDate(Date date) { ... } public Date getStartDate() { ... } ... //this is called ENCAPSULATION } file: modelInstructor.java package model ; public class Instructor { private int id ; private String name ; private String profession ; //setter and getter methods as shown earlier ... } 4
  • 5. file: modelStudent.java package model; public class Student { private int id ; private String name ; private int age ; private String phone ; //setter and getter methods as shown earlier ... } • Activity: How to automatically generate them with Netbeans IDE? If the system is modeled like this, business logic can be implemented easily in a talkative manner. As shown in the following business related functions written casually: Business Related Functions ... public void participateStudent(Student student, Course course) { course.getStudents().add(student) ; } public void participateInstructor(Instructor instructor, Course course) { course.setInstructor(instructor) ; } public void registerMySelf() { Instructor me = new Instructor() ; me.setName("abdalla mahmoud") ; me.setProfession("java") ; //javaCourse is an instance of Course representing our course participateInstructor(me, javaCourse) ; } ... 1.2. The Need for Persistence Using objects for representing the state of the enterprise is a good idea for simplifying business logic programming, but objects are not durable as they are killed when the system 5
  • 6. shutdowns. Objects should be persisted in a database for two main reasons. First, if the system crashes, objects can be built again. Second, memory is too limited to hold enterprise data. In other words, objects should be synchronized with a database. Any changes made to the state of the objects should be reflected to the database. This problem is called mapping and discussed soon. 2. Object-to-Relational Mapping (ORM) Object-to-relational mapping is the problem of mapping objects and their attributes in memory to tables and columns in a relational database. • Every class is mapped to a table. • Every attribute is mapped to column. • Every object should be mapped to a row. • State should be synchronized with the row. Java Persistence API (JPA) provides a complete framework for mapping POJOs to relational databases. It works over JDBC API and provides an interface for a virtual object-oriented database, that's actually mapped to a relational database. The application server provides an implementation to the Java Persistence API to the components that integrates them with the relational database. The service synchronizes a set of entity beans and provided through the entity manager interface. 2.1. Entity Beans Entity beans are POJOs whose properties are encapsulated as shown earlier with setter and getter methods. Entity beans are instances of entity classes. Entity classes are annotated with @Entity. 6
  • 7. 2.2. Entity Manager The entity manager is the provider to the persistence service. It's a java interface that can be in injected to an implementation by the application server. Persistence service is configured using XML as persistence units and used by business components through dependency injection. 2.3. Example 2.3.1. Configuring a Data Source • Copy postgresql-8.3-604.jdbc4.jar (PostgreSQL JDBC Driver) to C:jbossserverdefaultlib • Copy C:jbossdocsexamplesjcapostgres-ds.xml to C:jbossserverdefaultdeploypostgres-ds.xml • Edit postgres-ds.xml: JDBC URL, username, and password of database connection with PostgreSQL. • Run JBoss Application Server. • A JDBC connection is bound to the JNDI with name (java:PostgresDS). 2.3.2. Configuring a Persistence Unit • Every EJB module (.jar) may contain a configuration file for persistence service. • File should be located in JAR_ROOTMETA-INFpersistence.xml • This is an example for the persistence configuration file: file: META-INFpersistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="FooPU" transaction-type="JTA"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <jta-data-source>java:PostgresDS</jta-data-source> <properties> <property name="hibernate.hbm2ddl.auto" value="update"/> <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/> </properties> </persistence-unit> </persistence> 2.3.3. Developing the Entity class file: modelInstructor.java package ent ; 7
  • 8. import javax.persistence.* ; /* This is the entity class of the Instructor table */ @Entity public class Instructor { @Id @GeneratedValue private int id ; private String name ; private String profession ; //setter and getter methods as shown earlier ... } 2.3.4. Developing the Session Bean file: entFooEJB.java package ent ; import javax.ejb.Stateless ; import javax.persistence.* ; /* This is the business component that will use the persistence service */ @Stateless public class FooEJB implements FooEJBRemote { @PersistenceContext(unitName="FooPU") EntityManager em ; public void foo() { Instructor bean = new Instructor() ; bean.setName("Abdalla Mahmoud") ; bean.setProfession("java") ; em.persist(bean) ; 8
  • 9. } } 2.3.5. Packaging the EJB Module • Create the folder META-INF in the C:workspace directory. • Create the persistence.xml file in the C:workspaceMETA-INF directory. • Compile and Package the EJB module as follows: Command Prompt C:workspace>javac entpack*.java C:workspace>jar cf module.jar entpack*.class META-INFpersistence.xml Here's the final directory structure of module.jar: 9
  • 10. 3. EntityManager 3.1. Persisting an Entity Persisting an entity makes it managed by the entity manager and changes are synchronized with the database. Example //entity is a reference to the entity em.persist(entity) ; 3.2. Retrieving an Entity Retrieving an entity is getting reference to it and makes it managed by the entity manager. Example //entity is a reference to the entity Instructor instructor = em.find(Instructor.class, primaryKey) ; 3.3. Deleting an Entity Removing an entity is deleting it from the database. Example //entity is a reference to the entity em.remove(entity) ; 3.4. Merging an Entity Merging an entity is making the entity managed by the entity manager the same as the given entity. Example //anotherEntity is a reference to another entity with other attributes em.merge(anotherEntity) ; 4. Schema Mappings By default, the entity manager maps tables and columns to the same name and types found in entity classes and attributes. For example, the earlier example is mapped to the following table: ID:Serial name:VARCHAR profession:VARCHAR 10
  • 11. Table: Instructor Some modifications or additions to the mapping may be needed in different circumstances. Mappings are annotated to the entity class and implemented by the entity manager. Here we will see some mappings provided by the JPA. 4.1. Basic Elementary Mappings 4.1.1. Table Mapping By default, entities are mapped to tables of the same name with its entity class. To modify the name, the entity is annotated with @Table and name is specified as follows: file: entInstructor.java package ent ; import javax.persistence.* ; @Entity @Table(name="HIQ_INSTRUCTORS") public class Instructor { @Id @GeneratedValue private int id ; private String name ; private String profession ; //setter and getter methods as shown earlier ... } 4.1.2. Column Mapping By default, entity variables are mapped to column of the same name with the variables. To modify the name, the variable is annotated with @Column and name is specified as follows: file: entInstructor.java package ent ; import javax.persistence.* ; 11
  • 12. @Entity @Table(name="HIQ_INSTRUCTORS") public class Instructor { @Id @GeneratedValue private int id ; @Column(name="INSTRUCTOR_NAME") private String name ; private String profession ; //setter and getter methods ... } Other attributes can be set to @Column: Attribute Purpose Default Value columnDefinition Exact DDL type. "" length length of VARCHAR fields. 255 nullable Can be null. true unique Should be unique. false 4.1.3. Primary Key Mapping Primary key attribute is mapped using @Id as shown earlier. @GeneratedValue makes the value of the primary key increases automatically. 4.2. Entity Relationships Mappings 4.2.1. OneToOne One-to-one relationship is mapped using @OneToOne. Example: file: entCourse.java package ent ; import java.util.ArrayList ; import java.util.Date ; import javax.persistence.* ; 12
  • 13. @Entity public class Course { @Id @GeneratedValue private String id ; private String name ; private Date startDate ; private Date endDate ; @OneToOne(cascade={CascadeType.ALL}) private Instructor instructor ; private ArrayList<Student> students = new ArrayList<Student>() ; //setter and getter methods ... } This is called unidirectional relationship, because only the Course refers to the Instructor. To make Instructor also referes to both, i.e. bidirectional, we can edit the Instructor class as follows: file: entInstructor.java package ent ; import javax.persistence.* ; @Entity @Table(name="HIQ_INSTRUCTORS") public class Instructor { @Id @GeneratedValue private int id ; @Column(name="INSTRUCTOR_NAME") private String name ; private String profession ; @OneToOne(mappedBy="instructor") private Course course ; //setter and getter methods ... 13
  • 14. } 4.2.2. OneToMany One-to-many relationship is mapped using @OneToMany. Example: file: entCourse.java package ent ; import java.util.ArrayList ; import java.util.Date ; import javax.persistence.* ; @Entity public class Course { @Id @GeneratedValue private String id ; private String name ; private Date startDate ; private Date endDate ; @OneToOne(cascade={CascadeType.ALL}) private Instructor instructor ; @OneToMany(cascade={CascadeType.ALL}) private ArrayList<Student> students = new ArrayList<Student>() ; //setter and getter methods ... } This is a unidirectional relationship. Bidirectional relationship can be implemented as shown earlier, but using @ManyToOne relationship instead. 4.2.3. ManyToMany Many-to-many relationship is mapped using @ManyToMany. 14