Professional Documents
Culture Documents
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
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
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
CRUD
• basic functions of persistent storage:
Persistent classes 7
• POJO classes whose instances will be stored in database tables
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() {}
}
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
@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
}
@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;
}
CREATE SEQUENCE Emp_Seq MINVALUE 1000 START WITH 1000 INCREMENT BY 100
• 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
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.
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
@Entity
FetchType.LAZY FetchType.EAGER
@OneToMany(mappedBy="customer, @OneToMany(mappedBy="customer,
fetch=FetchType.LAZY) fetch=FetchType.EAGER)
private List orders; private List orders;
} }
@Entity @Entity
public class Troop { public class Soldier {
@OneToMany(mappedBy="troop") @ManyToOne
public Set<Soldier> soldiers; @JoinColumn(name="troop_fk")
} public Troop troop;
}
@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;
}
@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;
@Entity @Entity
public class Product { public class Part {
...
@OneToMany }
@JoinColumn(name="PART_ID")
public Set<Part> parts
}
@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;
}
@Entity @Entity
public class Product { public class Part {
…
} @ManyToOne
@JoinColumn(name=“PROD_ID")
private Product product;
}
@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;
}
@Entity @Entity
public class Body { public class Heart {
@Id
@OneToOne public Long id;
@PrimaryKeyJoinColumn }
//@JoinColumn(name=“heart_id”)
public Heart heart;
}
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
Native Query
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
Named Query
Advantages:
Static queries
Centralized declaration
Build process can validate named queries
Cached and translated at runtime
Disadvantages:
Not customizable at runtime (not dynamic)
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);
• 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));
Criteria Builder
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
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