Hibernate

Architecture

  flowchart TB
	App[Java Application]
	PO[Persistence Objects]
	subgraph Hibernate
	T[Transaction]
	C[Configuration]
	SF[Session_Factory]
	S[Session]
	Q[Query]
	FLC[First_Level_Cache]
	end
	SLC[Second_Level_Cache]
	DB[(Database)]

	App --> PO

	S --> PO

	SF --> C
	S --> SLC

	S --> Q --> FLC

	Hibernate --> DB

	S -->  SF
  • Configuration Object : Holds configuration properties of Hibernate

    • Two Components
      • Database Connection
      • 配置 class 的映射
  • SessionFactory Object : 由 Configuration Object 實例化

    • client : ConnectionProvider
    • Holds second-level cache(optional)
    • can one SessionFactory per database
  • Session Object :

可以視為介於Application和DB之間的一個介面
  • Short-Lived Object : 此物件(也是個Factory)包含

    • JDBC Connection
    • org.hibernate.Session interface provides methods
      • insert
      • update
      • delete
      • First-Level Cache of data
  • Transaction interface :

Used to manipulate the persistent objects (creation, retrieving data …) using SQL or HQL
  • Query interface :
Manipulate the persistent objects (creation, retrieving data …) using SQL or HQL
  • Criteria :

Lifecycle

  flowchart TB

		O((Object))
		TS(Transient_State)
		PS(Persistent_State)
		DS(Detached_Sate)
		RS(Removed_Sate)
		E((End))

		O --->|New isntance of entiy| TS
		O --->|get,load| PS

		TS --->|save,persist,saveOrUpdate,update| PS
		TS --->|Garbage| E

		PS --->|delete| RS
		PS --->|detach,close,clear,evict| DS

		DS --->|save,saveOrUpdate,merge,lock| PS
		DS --->|Garbage| E

Transient State

  • The object is not associated with any Hibernate session
  • The object is simply a plain Java object (POJO) that is not yet persisted in the database.

Persistent State

When an object is associated with a Hibernate session, it enters the persistent state. In this state, the object is associated with a specific Hibernate session and is actively managed by Hibernate. Any changes made to the object will be tracked by Hibernate and will be persisted to the database when the session is flushed.

Two sub-states of the persistent state

Transient->Persistent State

Persistent->Detached State

Detached State

Removed State

First-Level Cache

Pros

  • 減少 JDBC 的 boiler-plate code
  • Hibernate Cache 提供更好的 performance
  • 提供 Proxy Object 來支援 Lazy Init