A guide to Hibernate
ORM: Object/Relation Mapping
● map object
● map relationship
Hibernate ORM
● An ORM solution, effectively “sits between” the Java application and the Relational Database
● A powerful, high performance Object-Relational Persistence and Query service for any Java Application
● Hibernate maps Java classes to database tables and from Java data types to SQL data types
Hibernate sits between traditional Java objects and database server to handle all the work in persisting those objects based on the appropriate O/R mechanisms and patterns.
Step for use Hibernate
step 1
● Create a Maven project
● add dependencies to pom file: hibernate & mysql
step 2 — pom file and project structure
step 3 — Bootstrap a JPA EntityManagerFactory
Bootstrap means initializing and starting a software component.
In Hibernate, we are specifically talking about the process of building a fully
functional SessionFactory instance or EntityManagerFactory instance, for JPA.
JPA-standardized bootstrapping is highly recommended.
In Java SE environments the persistence provider (Hibernate in this case) is
required to locate all JPA configuration files by classpath lookup of the
META-INF/persistence.xml resource name
sample persistence.xml file
step 4 — Create entity class
○ required: @Entity
○ optional: @Table (name =“tstudent”)
Step 5 — Using JPA APIs
Step 6 — Run main method
Basic O/R Mapping
Mapping PO and Simple Properties
● @Entity
A POJO annotated with @Entity will be persisted by Hibernate.
● @Table
Define the table the entity will be persisted into.
● @Column
Specify the details of the column to which a field or property will be mapped.
● @Transient
Ignored by the entity manager
Mapping Identifiers
● simple identifier:
○ @Id: defines the mapping from the property to the primary key column
○ @GeneratedValue and strategy
● composite identifiers:
○ use a component type to represent the identifier and map it as a property in the entity
■ @EmbeddedId @Embeddable
○ map multiple properties as @Id properties (only supported by Hibernate)
■ @IdClass
Note:
● implements java.io.Serializable
● override equals() and hashCode()
important EntityManager API
● persist — for new entity should always use persist which will attach the
entity to the current persistence context. Will generate an insert
statement
when you run persist(), will get these info:
● merge — used for detached entity update, will generate a select and an
update statement
● remove — delete an entitry from DB row
● find — find an entity with the given id, will attach the found entity to the
current persistence context. So update a managed entity will implicitly
synced to DB after transaction commit
● contains — check if the entity is managed in current persistence context or
no
● detach — remove the given entity from persistence context