1. JPA
1.1. Overview
The process of mapping Java objects to database tables and vice versa is called "Object-relational mapping" (ORM).The Java Persistence API (JPA) is one possible approach to ORM. JPA is a specification and several implementations are available. Popular implementations are Hibernate, EclipseLink and Apache OpenJPA. The reference implementation of JPA is EclipseLink.
Via JPA the developer can map, store, update and retrieve data from relational databases to Java objects and vice versa.
JPA permits the developer to work directly with objects rather then with SQL statements. The JPA implementation is typically called persistence provider. JPA can be used in Java-EE and Java-SE applications.
The mapping between Java objects and database tables is defined via persistence metadata. The JPA provider will use the persistence metadata information to perform the correct database operations.
JPA typically defines the metadata via annotations in the Java class. Alternatively the metadata can be defined via XML or a combination of both. A XML configuration overwrites the annotations.
The following description will be based on the usage of annotations.
JPA defines a SQL-like Query language for static and dynamic queries.
Most JPA persistence provider offer the option to create automatically the database schema based on the metadata.
A class which should be persisted in a database it must be
annotated
with
All entity classes must define a primary key, must have a non-arg constructor and or not allowed to be final. Keys can be a single field or a combination of fields.
JPA allows to auto-generate the primary key in the database via the
By default, the table name corresponds to the class name. You can change this with the addition to the annotation @Table(name="NEWTABLENAME").
javax.persistence.Entity
. Such a class is called
Entity
. JPA will create a table for the entity in your database.
Instances
of the class will be a row in the table.
All entity classes must define a primary key, must have a non-arg constructor and or not allowed to be final. Keys can be a single field or a combination of fields.
JPA allows to auto-generate the primary key in the database via the
@GeneratedValue
annotation.
By default, the table name corresponds to the class name. You can change this with the addition to the annotation @Table(name="NEWTABLENAME").
The fields of the Entity will be saved in the database. JPA can use
either your instance variables (fields) or the corresponding getters
and setters to access the fields. You are not allowed to mix both
methods. If you want to use the setter and getter methods the Java
class must follow the Java Bean naming conventions. JPA persists per
default all fields of an Entity, if fields should not be saved they
must be marked with
By default each field is mapped to a column with the name of the field. You can change the default name via
The following annotations can be used.
A relationship can be bidirectional or unidirectional, e.g. in a bidirectional relationship both classes store a reference to each other while in an unidirectional case only one class has a reference to the other class. Within a bidirectional relationship you need to specify the owning side of this relationship in the other class with the attribute "mappedBy", e.g. @ManyToMany(mappedBy="attributeOfTheOwningClass".
Entities which are managed by an Entity Manager will automatically propagate these changes to the database (if this happens within a commit statement). If the Entity Manager is closed (via close()) then the managed entities are in a detached state. If synchronize them again with the database a Entity Manager provides the merge() method.
The persistence context describes all Entities of one Entity manager.
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private String id;
private String firstName;
private String lastName;
private Family family;
private String nonsenseField = "";
private List jobList = new ArrayList();
public String getId() {
return id;
}
public void setId(String Id) {
this.id = Id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
// Leave the standard column name of the table
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@ManyToOne
public Family getFamily() {
return family;
}
public void setFamily(Family family) {
this.family = family;
}
@Transient
public String getNonsenseField() {
return nonsenseField;
}
public void setNonsenseField(String nonsenseField) {
this.nonsenseField = nonsenseField;
}
@OneToMany
public List getJobList() {
return this.jobList;
}
public void setJobList(List nickName) {
this.jobList = nickName;
}
}
@Transient
.
By default each field is mapped to a column with the name of the field. You can change the default name via
@Column
(name="newColumnName").
The following annotations can be used.
1.4. Relationship Mapping
JPA allows to define relationships between classes, e.g. it can be defined that a class is part of another class (containment). Classes can have one to one, one to many, many to one, and many to many relationships with other classes.A relationship can be bidirectional or unidirectional, e.g. in a bidirectional relationship both classes store a reference to each other while in an unidirectional case only one class has a reference to the other class. Within a bidirectional relationship you need to specify the owning side of this relationship in the other class with the attribute "mappedBy", e.g. @ManyToMany(mappedBy="attributeOfTheOwningClass".
1.5. Entity Manager
The entity managerjavax.persistence.EntityManager
provides the operations from and to the database, e.g.
find objects,
persists them, remove objects from the
database, etc.
In a JavaEE
application the entity manager is automatically
inserted in the web
application. Outside JavaEE you need to
manage the entity manager
yourself.
Entities which are managed by an Entity Manager will automatically propagate these changes to the database (if this happens within a commit statement). If the Entity Manager is closed (via close()) then the managed entities are in a detached state. If synchronize them again with the database a Entity Manager provides the merge() method.
The persistence context describes all Entities of one Entity manager.
The
EntityManager
is created by the
EntitiyManagerFactory
which is configured by the persistence unit. The persistence unit is
described via the file "persistence.xml" in the directory META-INF in
the source folder. A set of entities which are logical connected will
be grouped via a persistence unit. "persistence.xml" defines the
connection data to the database, e.g. the driver, the user and the
password, 2. Simple Example
Create a java Project. Create a
folder
"lib" and place the
required
JPA jars and derby.jar into this folder.
package web.com.jpamodel;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class DoSomething{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long i;
private String a;
private String b;
public String getA() {
return summary;
}
public void setA(String A) {
this.summary = summary;
}
public String getB() {
return description;
}
public void setB(String B) {
this.description = description;
}
}
package web.com.jpamodel;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Family {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private int id;
private String description;
@OneToMany(mappedBy = "family")
private final List members = new ArrayList();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List getMembers() {
return members;
}
}
/**********************************************************************/
package web.com.jpamodel;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class DoSomething{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long i;
private String a;
private String b;
public String getA() {
return summary;
}
public void setA(String A) {
this.summary = summary;
}
public String getB() {
return description;
}
public void setB(String B) {
this.description = description;
}
}
3. Relationship Example
Create a Java project, create again a folder "lib" and place the required JPA jars and derby.jar into this folder.package web.com.jpamodel;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Family {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private int id;
private String description;
@OneToMany(mappedBy = "family")
private final List members = new ArrayList();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List getMembers() {
return members;
}
}
/**********************************************************************/
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private String id;
private String firstName;
private String lastName;
private Family family;
private String nonsenseField = "";
private List jobList = new ArrayList();
public String getId() {
return id;
}
public void setId(String Id) {
this.id = Id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
// Leave the standard column name of the table
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@ManyToOne
public Family getFamily() {
return family;
}
public void setFamily(Family family) {
this.family = family;
}
@Transient
public String getNonsenseField() {
return nonsenseField;
}
public void setNonsenseField(String nonsenseField) {
this.nonsenseField = nonsenseField;
}
@OneToMany
public List getJobList() {
return this.jobList;
}
public void setJobList(List nickName) {
this.jobList = nickName;
}
}
/***********************************************************************/
package web.com.jpamodel;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Job {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private int id;
private double salery;
private String jobDescr;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getSalery() {
return salery;
}
public void setSalery(double salery) {
this.salery = salery;
}
public String getJobDescr() {
return jobDescr;
}
public void setJobDescr(String jobDescr) {
this.jobDescr = jobDescr;
}
}
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Job {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private int id;
private double salery;
private String jobDescr;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getSalery() {
return salery;
}
public void setSalery(double salery) {
this.salery = salery;
}
public String getJobDescr() {
return jobDescr;
}
public void setJobDescr(String jobDescr) {
this.jobDescr = jobDescr;
}
}
No comments:
Post a Comment