Hibernate Dev Process - To do List
1. Add Hibernate Configuration file
2. Annotate Java Class
3. Develop Java code to perform database operations
Entity Class: Java class that is mapped to a database table.
Two options for Mapping
1. XML config file (legacy)
2. Java Annotations (modern, preferred)
Java Annotations
1. Map class to database table
2. Map fields to database columns
SessionFactory :
Reads the hibernate config file.
Creates Session Objects
Heavy-weight Object
Only create once in your app
Session
Wraps a JDBC connection
Main Object used to save/retrieve objects
Short-lived object
Retrieved from SessionFactory
Primary key ID Generation Strategies
GenerationType.AUTO : Pick an appropriate strategy for the particular database
GenerationType.IDENTITY : Assign primary keys using database identity column
GenerationType.SEQUENCE : Assign primary keys using a database sequence
GenerationType.TABLE : Assign primary keys using an underlying database table to ensure uniqueness
custom ID generation
We can define your own CUSTOM generation strategy
Create implementation of org.hibernate.id.IdentifierGenerator
Override the method public Serializable generate()
https://www.baeldung.com/querydsl-with-jpa-tutorial
hibernate dialect
https://www.javatpoint.com/dialects-in-hibernate
In hibernate we will begintranscation and and commit the transaction for select as well whereas in sql we will do that only for DML script
Hibernate Query Language (HQL)
Query language for retrieving objects
similar in nature to SQL
where, like, order by, join, in, etc ...
Advance Mapping
One - to - One
One - to - Many, Many - to - One
Many - to - Many
Important Database concepts
Primary key and Foreign key
Cascade
Cascade:
You can cascade operations
Apply the same operations to related entities
Uni-Directional
Bi-Directional
Referential Integrity
Entity LifeCycle
Detach : If entity is detached, it is not associated with a Hibernate session
Merge: If instance is detached from session, then merge will reattach to session
Persist: Transitions new instance to managed state. Next flush/commit will save in db
Remove: Transitions managed entity to be removed. Next flush/commit will delete from db
Refresh: Reload/synch object with data from db. Prevents stale data
Cascade Types
PERSIST : If entity is persisted/saved , related entity will also be persisted
REMOVE: If entity is removed/deleted, related entity will also be deleted
REFRESH: If entity is refreshed, related entity will also be refreshed
DETACH : If entity is detached(not associated w/ session), then related entity will also be detached.
MERGE : If entity is merged, then related entity will also be merged
ALL : All of above cascade types
mappedBy
Look at the
Annotations
@Entity
@Table
@Id
@Column
@GeneratedValue
@OneToOne
@ManyToOne
@OneToMany
@ManytoMany
@JoinColumn