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 Course Info2
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 annotation: import public class Employee {... } JPA will attempt to use the classname as a table name, and the attribute names as column names IS Course Info3
Persistence Unit and entities All classes annotated are included in the PU Additional classes may be included: Classes with entries in xml mapping files Classes listed in elements in persistence.xml You can use persistence.xml to exclude classes: use an element use elements to include the entities you want No other classes will be included! Even Åby Larsen IS-102 Introduksjon4
JPA Id annotations annotations is used to specify the primary key. annotation can be used to specify automatic generation of the primary key values import public class private long empNo;... } IS Course Info5
@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 public class private long empNo; public boolean equals(Object o) {... return this.empNo == that.empNo; } Even Åby Larsen IS-102 Introduksjon6
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 IS-102 Introduksjon7
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 IS-102 Introduksjon8