• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Persistence
 

Persistence

on

  • 1,575 views

 

Statistics

Views

Total Views
1,575
Views on SlideShare
1,573
Embed Views
2

Actions

Likes
0
Downloads
33
Comments
0

1 Embed 2

http://www.linkedin.com 2

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Persistence Persistence Document Transcript

    • 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