You are on page 1of 43

QUALITY. PRODUCTIVITY. INNOVATION.

Hibernate –
ORM Framework
Interns have never been this
lucky

endava.com
 ORM
Hibernate ORM  JPA & Hibernate
 Hibernate Architecture
 CRUD Operations
 Mapping Declaration
 Persistence Annotations and Mappings
 Inheritance Strategy
 Entity States
 Working with entities
 Cascade Types
 Fetch Types
 Associations (Relationships)
 Query Types
 Transaction Management - ACID

2 QUALITY. PRODUCTIVITY. INNOVATION.


ORM

ORM (Object/Relational Mapping)


• is a programming technique for converting data between incompatible type systems like relational databases in object-oriented
programming languages

Impedance mismatch
• represents the differences between the relational model and the domain model

3
Pros
• portable – write the domain model once and the ORM layer will handle the statements for different DBMS
• Rapid Application Development – less code to write and maintain, easy data nesting by cascading operations and transaction
management support

Cons
• learn a new language
• speed – raw SQL is faster as there is no translation layer, complex queries may need additional tuning

3 QUALITY. PRODUCTIVITY. INNOVATION.


ORM

ORM (Object/Relational Mapping)


• is a programming technique for converting data between incompatible type systems like relational databases in object-oriented
programming languages

Impedance mismatch
• represents the differences between the relational model and the domain model

4
Pros
• portable – write the domain model once and the ORM layer will handle the statements for different DBMS
• Rapid Application Development – less code to write and maintain, easy data nesting by cascading operations and transaction
management support

Cons
• learn a new language
• speed – raw SQL is faster as there is no translation layer, complex queries may need additional tuning

4 QUALITY. PRODUCTIVITY. INNOVATION.


Hibernate Architecture Overview

5 QUALITY. PRODUCTIVITY. INNOVATION.


Java Persistence API vs Hibernate Native API

Java Persistence API:

EntityManagerFactory entityManagerFactory= Persistence.createEntityManagerFactory("example");


EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(new Employee(id, "name", "department"));
entityManager.getTransaction().commit();
entityManager.close();
6
Hibernate Native API:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();


Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(new Employee(id, "name", "department"));
session.getTransaction().commit();
session.close();

6 QUALITY. PRODUCTIVITY. INNOVATION.


CRUD Operations

CRUD
• basic functions of persistent storage:

Persistent classes 7
• POJO classes whose instances will be stored in database tables

public class Employee {


private int id;
public Employee(){};
public int getId() { return id; }
public void setId( int id ) { this.id = id; }
}

7 QUALITY. PRODUCTIVITY. INNOVATION.


CRUD Operations
JPA & Hibernate API

//JPA //Hibernate API


//Create //Create
entityManager.persist(employee); session.save(employee);
//Read //Read
company.setManager(entityManager.getReference(Empl company.setManager(session.load(Employee.class,
oyee.class, employeeId)); employeeId));
8
Employee employee = Employee employee = session.get(Employee.class,
entityManager.find(Employee.class, employeeId); employeeId);
//Update – set property then flush //Update – set property then flush
entityManager.flush(); session.flush();
//Merge //Merge
employee = entityManager.merge(employee); employee = session.merge(employee);
//Delete //Delete
entityManager.remove(employee); session.delete(employee);

8 QUALITY. PRODUCTIVITY. INNOVATION.


Mapping Declaration

Object/relational mappings are defined in three ways:

• using JPA annotations

• using JPA XML deployment descriptors (orm.xml)


9
• using Hibernate XML files (hbm.xml)

9 QUALITY. PRODUCTIVITY. INNOVATION.


Table Mapping

Only the @Entity and @Id annotations need to be specified to create and map an entity to a database table

@Entity
@Table(name = “EMPLOYEE”, schema = “DEMO”)
public class Employee implements Serializable {
@Id 10
private int id;

public Employee() {}
}

10 QUALITY. PRODUCTIVITY. INNOVATION.


Persistence Annotations

Mapping types

• Value types
• Basic types
• Embeddable types
• Collection types
• Entity types 11

Access strategies
@Id
private Integer id;
• Field-based access
• Property-based access @Id
public Integer getId() {
return id;
}
11 QUALITY. PRODUCTIVITY. INNOVATION.
Mapping Simple Types
Hibernate type JDBC type Java type

• @Basic – assumed by default StringType VARCHAR java.lang.String

MaterializedClob CLOB java.lang.String


@Basic (optional = true, fetch = FetchType.EAGER) TextType LONGVARCHAR java.lang.String
private String name; CharacterType CHAR char, java.lang.Character

BooleanType BIT boolean, java.lang.Boolean

Validations (JPA): ByteType TINYINT byte, java.lang.Byte


• @Max(value= )
IntegerTypes INTEGER int, java.lang.Integer
• @Min(value= )
• @Null 12
LongType BIGINT long, java.lang.Long

• @NotNull FloatType FLOAT float, java.lang.Float

• @Past DoubleType DOUBLE double, java.lang.Double

• @Future BigIntegerType NUMERIC java.math.BigInteger

BigDecimalType NUMERIC java.math.BigDecimal


Validations (Hibernate API):
TimestampType TIMESTAMP java.sql.Timestamp
• @Email
• @Length TimeType TIME java.sql.Time

• @NotBlank DateType DATE java.sql.Date


• @NotEmpty
• @URL

12 QUALITY. PRODUCTIVITY. INNOVATION.


Column Mappings
@Column @Entity
@Lob
public class Employee {
@Id
• BLOBs (binary large objects) @Column(name="EMP_ID")
• byte[], Byte[], Serializable types private int id;
• CLOBs (character large objects) private String name;
• char[], Character[], String @Column(name="SAL")
@Enumerated private long salary;
• EnumType.STRING @Basic(fetch=FetchType.LAZY)
• EnumType.ORDINAL - default @Lob
13
@Temporal @Column(name=“EMP_PHOTO")
• TemporalType.DATE
private byte[] photo;
• TemporalType.TIME @Column(name = “EMP_TYPE”)
• TemporalType.TIMESTAMP @Enumerated(EnumType.STRING)
private EmployeeType type;
@Transient
@Temporal(TemporalType.DATE)
private Date employmentDate;
public enum EmployeeType { @Transient
FULLTIME_EMPLOYEE, PARTTIME_EMPLOYEE private String bankAccount;
} };
13 QUALITY. PRODUCTIVITY. INNOVATION.
Mapping Persistent Classes

@Entity
@Table(name = “EMPLOYEE”)
public class Employee implements Serializable {
@Id
@Column(name = “id”)
private int id;
14
@Column(name = “name”, length=60, nullable = false)
private String name;

public Employee(){};
//getters & setters
}

14 QUALITY. PRODUCTIVITY. INNOVATION.


Identity Generation

@GeneratedValue
Strategies: @Entity
• AUTO public class Employee {
• TABLE @Id @GeneratedValue(strategy=GenerationType.AUTO)

private int id;
SEQUENCE
}
• IDENTITY 15
@Entity
public class Employee {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
}

15 QUALITY. PRODUCTIVITY. INNOVATION.


Generation Strategies
@TableGenerator(name=“Emp_Gen”, table=“ID_GEN”, pkColumnName=“GEN_NAME”,
valueColumnName=“GEN_VAL”, initialValue=1000, allocationSize=100)
@Id @GeneratedValue(generator=“Emp_Gen”)
private int id;
CREATE TABLE ID_GEN (
GEN_NAME VARCHAR(80),
GEN_VAL INTEGER,
CONSTRAINT PK_ID_GEN
PRIMARY KEY (GEN_NAME) 16
);
INSERT INTO ID_GEN (GEN_NAME , GEN_VAL ) VALUES (‘Emp_Gen’, 1000);

@SequenceGenerator(name = “Emp_Gen”, sequenceName = “Emp_Seq”)


@Id @GeneratedValue(generator = “Emp_Gen”)
private int id;

CREATE SEQUENCE Emp_Seq MINVALUE 1000 START WITH 1000 INCREMENT BY 100

16 QUALITY. PRODUCTIVITY. INNOVATION.


Inheritance Strategy

Several strategies are possible to persist a class hierarchy:

• Single table mapping strategy (InheritanceType.SINGLE_TABLE) - properties of all subclasses in a given mapped class
hierarchy are stored in a single table

• Table per concrete class strategy (InheritanceType.TABLE_PER_CLASS) - each concrete class is mapped to a separate table
17
• Joined subclass strategy (InheritanceType.JOINED) - separate tables per class and subclasses, subclasses do not contain
columns for inherited properties

17 QUALITY. PRODUCTIVITY. INNOVATION.


Inheritance Mapping
Single table mapping strategy
@Entity CREATE TABLE EMPLOYEE (
@Table(name = "EMPLOYEE") ID serial UNIQUE NOT NULL,
@Inheritance(strategy = InheritanceType.SINGLE_TABLE) FIRSTNAME varchar(255),
@DiscriminatorColumn(name = "EMPLOYEE_TYPE", discriminatorType = DiscriminatorType.CHAR) SURNAME varchar(255),
@DiscriminatorValue("E") DEPARTMENT varchar(255),
public class Employee { EMPLOYEE_TYPE char(1),
SALARY integer,
private int id;
HOURLY_RATES integer,
private String department; PERIOD integer
} )
@Entity
@Table(name = "EMPLOYEE") 18
@DiscriminatorValue("P")
public class ParttimeEmployee extends Employee {
private int hourlyRates;
private int period;
}
@Entity
@Table(name = "EMPLOYEE")
@DiscriminatorValue("F")
public class FulltimeEmployee extends Employee {
private int salary;
}
18 QUALITY. PRODUCTIVITY. INNOVATION.
Inheritance Mapping
Table per concrete class strategy

@Entity CREATE TABLE EMPLOYEE (


@Table(name = “EMPLOYEE”) ID serial UNIQUE NOT NULL,
FIRSTNAME varchar(255),
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
SURNAME varchar(255),
public class Employee implements Serializable { DEPARTMENT varchar(255)
private int id; );
private String firstname;
private String surname; CREATE TABLE FULLTIME_EMPLOYEE (
private String department; ID serial UNIQUE NOT NULL,
FIRSTNAME varchar(255),
} 19 SURNAME varchar(255),
@Entity
DEPARTMENT varchar(255),
@Table(name = “PARTTIME_EMPLOYEE”) SALARY integer
public class ParttimeEmployee extends Employee { );
private int hourlyRates;
private int period; CREATE TABLE PARTTIME_EMPLOYEE (
} ID serial UNIQUE NOT NULL,
@Entity FIRSTNAME varchar(255),
SURNAME varchar(255),
@Table(name = “FULLTIME_EMPLOYEE”)
DEPARTMENT varchar(255),
public class FulltimeEmployee extends Employee { HOURLY_RATES integer,
private int salary; PERIOD integer
} );

19 QUALITY. PRODUCTIVITY. INNOVATION.


Inheritance Mapping
Joined subclass strategy
@Entity CREATE TABLE EMPLOYEE (
@Table(name = “EMPLOYEE”) ID serial UNIQUE NOT NULL,
@Inheritance(strategy = InheritanceType.JOINED) FIRSTNAME varchar(255),
public class Employee { SURNAME varchar(255),
private int id; DEPARTMENT varchar(255)
private String firstname; );
private String surname;
CREATE TABLE FULLTIME_EMPLOYEE (
private String department; EMP_ID integer UNIQUE NOT NULL,
} SALARY integer
@Entity );
@Table(name = “PARTTIME_EMPLOYEE”) 20
@PrimaryKeyJoinColumn(name = “EMP_ID”) CREATE TABLE PARTTIME_EMPLOYEE (
public class ParttimeEmployee extends Employee { EMP_ID integer UNIQUE NOT NULL,
HOURLY_RATES integer,
private int hourlyRates;
PERIOD integer
private int period; );
}
@Entity
@Table(name = “FULLTIME_EMPLOYEE”)
@PrimaryKeyJoinColumn(name = “EMP_ID”)
public class FulltimeEmployee extends Employee {
private int salary;
}
20 QUALITY. PRODUCTIVITY. INNOVATION.
Entity States

 Transient - When it is just created and has no primary key, the state is called transient.
 Persistent - You can make a transient instance persistent by associating it with a Session. A persistent
instance has a representation in the database, an identifier value and is associated with a Session.
 Detached - Once we close the Hibernate Session, the persistent instance will become a detached instance.

21 QUALITY. PRODUCTIVITY. INNOVATION.


Working with entities

 EntityManager
 Used to manage entity instances on a specific database
 Create, update, remove, delete, find by primary key, query
 EntityManagerFactory
 Provides entity manager instances that connect to the same database
 Heavy object (because it’s a factory) 22
 Persistence Context (container-managed Entity Managers)
 A persistence context handles a set of entities which hold data to be persisted in some persistence
store (e.g. a database). In particular, the context is aware of the different states an entity can have
(e.g. managed, detached) in relation to both the context and the underlying persistence store.

22
Cascade Types

CascadeType: ALL, PERSIST, REMOVE, DETACH, MERGE, REFRESH

@Entity

public class Owner {


@OneToOne (cascade=CascadeType.ALL) 23
private DrivingLicense license;

@OneToMany(mappedBy="owner", cascade={CascadeType.PERSIST, CascadeType.REMOVE})

private Collection cars;


}

23 QUALITY. PRODUCTIVITY. INNOVATION.


Fetch Types

FetchType.LAZY FetchType.EAGER

@Entity(name = "CUSTOMER") @Entity(name = "CUSTOMER")


public class Customer { public class Customer {

@OneToMany(mappedBy="customer, @OneToMany(mappedBy="customer,
fetch=FetchType.LAZY) fetch=FetchType.EAGER)
private List orders; private List orders;
} }

24 QUALITY. PRODUCTIVITY. INNOVATION.


Associations

 Bidirectional - A bidirectional association allows navigation from both "ends" of the


association. Two kinds of bidirectional association are supported:
 OneToMany – set or bag valued at one end and single valued at the other
 ManyToMany – set or bag valued at both ends

25 QUALITY. PRODUCTIVITY. INNOVATION.


Associations

 Bidirectional - A bidirectional association allows navigation from both "ends" of the


association. Two kinds of bidirectional association are supported:
 OneToMany – set or bag valued at one end and single valued at the other (many-to-one owner)
 ManyToMany – set or bag valued at both ends

@Entity @Entity
public class Troop { public class Soldier {
@OneToMany(mappedBy="troop") @ManyToOne
public Set<Soldier> soldiers; @JoinColumn(name="troop_fk")
} public Troop troop;
}

26 QUALITY. PRODUCTIVITY. INNOVATION.


Associations

 Bidirectional - A bidirectional association allows navigation from both "ends" of the


association. Two kinds of bidirectional association are supported:
 OneToMany – set or bag valued at one end and single valued at the other (one-to-many owner)
 ManyToMany – set or bag valued at both ends

@Entity
public class Troop { @Entity
@OneToMany public class Soldier {
@JoinColumn(name="troop_fk") @ManyToOne
public Set<Soldier> soldiers; @JoinColumn(name="troop_fk“, ,
} insertable=false, updatable=false)
public Troop troop;
}

27 QUALITY. PRODUCTIVITY. INNOVATION.


Associations

 Bidirectional - A bidirectional association allows navigation from both "ends" of the


association. Two kinds of bidirectional association are supported:
 OneToMany – set or bag valued at one end and single valued at the other
 ManyToMany – set or bag valued at both ends (Can you guess the owning side?)

@Entity }
public class Employer{ @Entity
public class Employee{
@ManyToMany
@JoinTable(name="EMPLOYER_EMPLOYEE",
joinColumns=@JoinColumn(name="EMPER_ID"),
@ManyToMany(mappedBy = "employees")
public List employers;
inverseJoinColumns=@JoinColumn(name="EMPEE_ID"
))
}
private List employees;

28 QUALITY. PRODUCTIVITY. INNOVATION.


Associations

 Unidirectional - A unidirectional association allows navigation only from one end of the


association.
 OneToMany
 …

@Entity @Entity
public class Product { public class Part {
...
@OneToMany }
@JoinColumn(name="PART_ID")
public Set<Part> parts
}

29 QUALITY. PRODUCTIVITY. INNOVATION.


Associations

 Unidirectional - A unidirectional association allows navigation only from one end of the


association.
 OneToMany (with joinTable)
 …

@Entity @Entity
public class Product { public class Part {
...
@OneToMany
}
@JoinTable(name="PRODUCT_PARTS",
joinColumns=@JoinColumn(name="PRODUCT_ID",
inverseJoinColumns=@JoinColumn(
name="PART_ID"))
public Set<Part> parts;
}

30 QUALITY. PRODUCTIVITY. INNOVATION.


Associations

 Unidirectional - A unidirectional association allows navigation only from one end of the


association.
 ManyToOne
 …

@Entity @Entity
public class Product { public class Part {

} @ManyToOne
@JoinColumn(name=“PROD_ID")
private Product product;
}

31 QUALITY. PRODUCTIVITY. INNOVATION.


Associations

 Unidirectional - A unidirectional association allows navigation only from one end of the


association.
 ManyToOne (with joinTable)
 …

@Entity @Entity
public class Product { public class Part {

} @ManyToOne
@JoinTable(name="PRODUCT_PARTS",
joinColumns=@JoinColumn(name="PART_ID",
inverseJoinColumns=@JoinColumn(
name="PRODUCT_ID"))
private Product product;
}

32 QUALITY. PRODUCTIVITY. INNOVATION.


Associations

 Unidirectional - A unidirectional association allows navigation only from one end of the


association.
 OneToOne
 …

@Entity @Entity
public class Body { public class Heart {
@Id
@OneToOne public Long id;
@PrimaryKeyJoinColumn }
//@JoinColumn(name=“heart_id”)
public Heart heart;
}

33 QUALITY. PRODUCTIVITY. INNOVATION.


Query Types

Dynamic Query (JPQL Query)

Query q = em.createQuery("SELECT e FROM Employee e“);


List<Employee> results = (List<Employee>) q.getResultList();

 Advantages:
 Fast development
 Make use of Object-Programming
 Dependent on user input

 Disadvantages:
 Costly translation from JPQL to SQL
 Any String concatenation will prevent query caching

34 QUALITY. PRODUCTIVITY. INNOVATION.


Query Types

Dynamic Query (JPQL Query) – Query Parameters

Query q = em.createQuery("SELECT e FROM Employee e


WHERE e.firstName = :firstName“);
List<Employee> results = (List<Employee>) q.setParameter(“firstName”,
“Gigi”).getResultList();

Query q = em.createQuery("SELECT e FROM Employee e


WHERE e.firstName = ?1“);
List<Employee> results =
List<Employee>).setParameter(1,“Gigi”).getResultList();

35 QUALITY. PRODUCTIVITY. INNOVATION.


Query Types

Dynamic Query (JPQL Query) – Query Results

Query q = em.createQuery("SELECT e FROM Employee e“);

List<Employee> results = (List<Employee>) q.getResultList();


List<Employee> results = (List<Employee>)
q.setMaxResults(10).getResultList();

36 QUALITY. PRODUCTIVITY. INNOVATION.


Query Types

Native Query

Query q = em.createNativeQuery("SELECT * FROM emp“, Employee.class);


List<Employee> results = (List<Employee>) q.getResultList();

 Advantages:
 Use the flexibility and power of SQL
 Can call stored procedures/functions, views and other SQL specific structures
 Some things are just easier to write in SQL
 No translation is necessary

 Disadvantages:
 Directly dependent on database and table structure
 Don’t use any of the advantages of JPA/ORM

37 QUALITY. PRODUCTIVITY. INNOVATION.


Query Types

Named Query

@NamedQuery(name="findEmpByDiscName", query="SELECT e FROM Employee e


WHERE e.discipline.name LIKE :discName");
List<Employee> results = (List<Employee>)
em.createNamedQuery(“findEmpByDeptName”).setParameter(“discName”,
“Development”).getResultList();

 Advantages:
 Static queries
 Centralized declaration
 Build process can validate named queries
 Cached and translated at runtime
 Disadvantages:
 Not customizable at runtime (not dynamic)

38 QUALITY. PRODUCTIVITY. INNOVATION.


Query Types

Criteria Builder

• JPQL
SELECT c FROM Country c

• Criteria API
CriteriaBuilder cb = em.getCriteriaBuilder();  
CriteriaQuery<Country> q = Root<Country> c = q.from(Country.class);
q.select(c);

39 QUALITY. PRODUCTIVITY. INNOVATION.


Query Types

Criteria Builder - parameters

• JPQL
SELECT c FROM Country c WHERE c.population > :p

• Criteria API
CriteriaBuilder cb = em.getCriteriaBuilder();  
CriteriaQuery<Country> q = Root<Country> c = q.from(Country.class);
ParameterExpression<Integer> p = cb.parameter(Integer.class);
q.select(c).where(cb.gt(c.get("population"), p));

40 QUALITY. PRODUCTIVITY. INNOVATION.


Query Types

Criteria Builder

 Criteria Builder Queries:


 Write your queries in a type-safe way
 Defined by instantiation of Java objects that represent query elements
 Errors can be detected earlier, during compilation rather than at runtime
 Preferred for dynamic queries that are built at runtime

 JPQL Queries:
 JPQL queries, which are very similar to SQL queries, are easier to use and understand
 JPQL queries may be preferred for simple static queries - string

41 QUALITY. PRODUCTIVITY. INNOVATION.


Transaction Management - ACID


Atomicity - requires that each transaction be "all or nothing"

Consistency - ensures that any transaction will bring the database from one
valid state to another

Isolation - determines how transaction integrity is visible to other users and
systems 42

Durability - ensures that once a transaction has been committed, it will
remain so

42
Thank you!

Luci Filote
Senior Software Developer

Lucian.Filote@Endava.com
en_lfilote

43 QUALITY. PRODUCTIVITY. INNOVATION.

You might also like