Click here to load reader
Upload
abdalla-mahmoud
View
1.232
Download
0
Embed Size (px)
Citation preview
Persistence
By: Abdalla Mahmoud1
Contents
Persistence ......................................................................................... 1Contents ........................................................................................... 11. Introduction................................................................................... 0
1.1. The Need for Business Modeling .................................................. 31.2. The Need for Persistence ............................................................ 5
2. Object-to-Relational Mapping (ORM).................................................. 62.1. Entity Beans ............................................................................. 62.2. Entity Manager ......................................................................... 72.3. Example................................................................................... 7
2.3.1. Configuring a Data Source .................................................... 72.3.2. Configuring a Persistence Unit ............................................... 72.3.3. Developing the Entity class ................................................... 72.3.4. Developing the Session Bean................................................. 82.3.5. Packaging the EJB Module..................................................... 9
3. EntityManager ...............................................................................103.1. Persisting an Entity...................................................................103.2. Retrieving an Entity ..................................................................103.3. Deleting an Entity.....................................................................103.4. Merging an Entity .....................................................................10
4. Schema Mappings..........................................................................104.1. Basic Elementary Mappings .......................................................11
4.1.1. Table Mapping....................................................................114.1.2. Column Mapping.................................................................114.1.3. Primary Key Mapping ..........................................................12
4.2. Entity Relationships Mappings ....................................................124.2.1. OneToOne .........................................................................124.2.2. OneToMany........................................................................144.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 enterprisesoftware. There's enormous amount of data that should be persisted and used for long yearseven if the system went down dozens of times. Typically, data is persisted in relationaldatabases. As in Java SE, we used JDBC to manipulate relational database managementsystems. Although JDBC is a full-features API, it's not usable in the case of developmententerprise software. To discuss that, we need to discuss two points: the need for businessmodeling, 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 mostsoftware engineering approaches, we use domain object models for representing entities andtheir relationships.
DomainThe context of the business itself. For example, the domain maybe HiQ Academy'sbusiness entities and structure. Entities include tangible and intangible real-worldobjects like a manger, an instructor, a student, a running course, etc. Relationshipsinclude students participating to a course, instructors teaching the course, etc.
ModelA representation.
Object ModelObject representation.
Domain Object ModelAn 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: model\Course.java
package model ;
import java.util.ArrayList ;import java.util.Date ;
public class Course {
//private member variablesprivate 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: model\Instructor.java
package model ;
public class Instructor {
private int id ;private String name ;private String profession ;
//setter and getter methods as shown earlier...
}
4
file: model\Student.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 talkativemanner. 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 courseparticipateInstructor(me, javaCourse) ;
}...
1.2. The Need for Persistence
Using objects for representing the state of the enterprise is a good idea for simplifyingbusiness 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 thesystem crashes, objects can be built again. Second, memory is too limited to hold enterprisedata. In other words, objects should be synchronized with a database. Any changes made tothe state of the objects should be reflected to the database. This problem is called mappingand discussed soon.
2. Object-to-Relational Mapping (ORM)
Object-to-relational mapping is the problem of mapping objects and their attributes inmemory 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 relationaldatabases. It works over JDBC API and provides an interface for a virtual object-orienteddatabase, that's actually mapped to a relational database. The application server provides animplementation to the Java Persistence API to the components that integrates them with therelational database. The service synchronizes a set of entity beans and provided through theentity manager interface.
2.1. Entity Beans
Entity beans are POJOs whose properties are encapsulated as shown earlier with setter andgetter methods. Entity beans are instances of entity classes. Entity classes are annotatedwith @Entity.
6
2.2. Entity Manager
The entity manager is the provider to the persistence service. It's a java interface that can bein injected to an implementation by the application server. Persistence service is configuredusing XML as persistence units and used by business components through dependencyinjection.
2.3. Example
2.3.1. Configuring a Data Source
• Copy postgresql-8.3-604.jdbc4.jar (PostgreSQL JDBC Driver) toC:\jboss\server\default\lib
• Copy C:\jboss\docs\examples\jca\postgres-ds.xmlto C:\jboss\server\default\deploy\postgres-ds.xml
• Edit postgres-ds.xml: JDBC URL, username, and password of databaseconnection 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_ROOT\META-INF\persistence.xml• This is an example for the persistence configuration file:
file: META-INF\persistence.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/persistencehttp://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: model\Instructor.java
package ent ;
7
import javax.persistence.* ;
/*This is the entity class of the Instructor table*/
@Entitypublic class Instructor {
@Id @GeneratedValueprivate int id ;private String name ;private String profession ;
//setter and getter methods as shown earlier...
}
2.3.4. Developing the Session Bean
file: ent\FooEJB.java
package ent ;
import javax.ejb.Stateless ;import javax.persistence.* ;
/*This is the business component that will use the persistence service*/
@Statelesspublic 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:\workspace\META-INF directory.• Compile and Package the EJB module as follows:
Command Prompt
C:\workspace>javac entpack\*.javaC:\workspace>jar cf module.jar entpack\*.class META-INF\persistence.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 synchronizedwith the database.Example
//entity is a reference to the entityem.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 entityInstructor 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 entityem.remove(entity) ;
3.4. Merging an Entity
Merging an entity is making the entity managed by the entity manager the same as thegiven entity.Example
//anotherEntity is a reference to another entity with other attributesem.merge(anotherEntity) ;
4. Schema Mappings
By default, the entity manager maps tables and columns to the same name and types foundin entity classes and attributes. For example, the earlier example is mapped to the followingtable:
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 wewill 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 modifythe name, the entity is annotated with @Table and name is specified as follows:
file: ent\Instructor.java
package ent ;
import javax.persistence.* ;
@Entity@Table(name="HIQ_INSTRUCTORS")public class Instructor {
@Id @GeneratedValueprivate 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. Tomodify the name, the variable is annotated with @Column and name is specified as follows:
file: ent\Instructor.java
package ent ;
import javax.persistence.* ;
11
@Entity@Table(name="HIQ_INSTRUCTORS")public class Instructor {
@Id @GeneratedValueprivate 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: ent\Course.java
package ent ;
import java.util.ArrayList ;import java.util.Date ;import javax.persistence.* ;
12
@Entitypublic class Course {
@Id @GeneratedValueprivate 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. Tomake Instructor also referes to both, i.e. bidirectional, we can edit the Instructor class asfollows:
file: ent\Instructor.java
package ent ;
import javax.persistence.* ;
@Entity@Table(name="HIQ_INSTRUCTORS")public class Instructor {
@Id @GeneratedValueprivate 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: ent\Course.java
package ent ;
import java.util.ArrayList ;import java.util.Date ;import javax.persistence.* ;
@Entitypublic class Course {
@Id @GeneratedValueprivate 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 shownearlier, but using @ManyToOne relationship instead.
4.2.3. ManyToMany
Many-to-many relationship is mapped using @ManyToMany.
14