SlideShare uma empresa Scribd logo
1 de 14
Baixar para ler 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a Persistence

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
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
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 FresherRemote DBA Services
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 

Último (20)

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 

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