IS-102 Introduksjon
Download
Report
Transcript IS-102 Introduksjon
IS-907 Java EE
JPA: Simple Object-Relational Mapping
Object-Relational-Mapping
•
•
Description of how an object model “maps” to a relational data model
•
Class to table(s)
•
Object properties (attributes) to columns or relations
The mapping can be described as
•
java source code annotations, or
•
in xml mapping files
•
xml mapping files override the source code annotations
IS-202 - Course Info
2
JPA Entity annotations
•
To mark a class as a persistent entity (i.e. that objects of the class can be
stored in a database), use the @Entity annotation:
import javax.persistence.Entity;
@Entity
public class Employee {
...
}
•
JPA will attempt to use the classname as a table name, and the attribute
names as column names
IS-202 - Course Info
3
Persistence Unit and entities
•
All classes annotated with @Entity are included in the PU
•
Additional classes may be included:
•
•
Classes with entries in xml mapping files
•
Classes listed in <class> elements in persistence.xml
You can use persistence.xml to exclude classes:
•
use an <exclude-unlisted-classes> element
•
use <class> elements to include the entities you want
•
No other classes will be included!
Even Åby Larsen ([email protected])
IS-102 Introduksjon
4
JPA Id annotations
•
The @Id annotations is used to specify the primary key.
•
The @GeneratedValue annotation can be used to specify automatic generation
of the primary key values
import javax.persistence.*;
@Entity
public class Employee {
@Id @GeneratedValue
private long empNo;
...
}
IS-202 - Course Info
5
@Id, primary key, and object identity
•
The primary key defines the identity of an entity
•
The equals method defines the identity of an object
•
They should yield the same result!
@Entity public class Employee {
@Id @GeneratedValue private long empNo;
public boolean equals(Object o) {
...
return this.empNo == that.empNo;
}
}
Even Åby Larsen ([email protected])
IS-102 Introduksjon
6
Mapping simple types
•
Fields of the following types are mapped automatically to a column with the
same name as the field:
•
byte, int, short, long, boolean, char, float, double
•
Byte, Integer, Short, Long, Boolean, Character, Float, Double
•
byte[], Byte[], char[], Character[]
•
java.math.BigInteger, java.math.BigDecimal
•
String
•
java.util.Date, java.util.Calendar
•
java.sql.Date, java.sql.Time. java.sql.Timestamp
•
enum types
•
Serializable classes
Even Åby Larsen ([email protected])
IS-102 Introduksjon
7
Field access mode
•
Mapping annotations can be put on the field itself, or on the get methods
•
If the fields are annotated, JPA will access the fields directly (bypassing the
private restriction) to get or set their value
•
If the get methods are annotated, JPA will use the get and set methods
•
all persistent fields must have getters and setters
Even Åby Larsen ([email protected])
IS-102 Introduksjon
8