SlideShare a Scribd company logo
1 of 14
Download to read offline
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

More Related Content

What's hot (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
 

Similar to Persistence

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
 
[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
 
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
Pieter 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_guide
ice1oog
 
Access tutorial (1)
Access tutorial (1)Access tutorial (1)
Access tutorial (1)
yersyorrego
 

Similar to Persistence (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
 

More from Abdalla Mahmoud

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

More from 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
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

Persistence

  • 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