- Add dependencies: Hibernate and MySQL connector
- Create database [create-db.sql]
- Configure Hibernate by XML [hibernate.cfg.xml]
- CRUD features
- SessionFactory, Session and Transaction
- Uni-directional and bi-directional relationship
- Cascade types: CascadeType.ALL, CascadeType.PERSIST (save), CascadeType.REMOVE, CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH
- 📌 Use persist() with CascadeType.ALL/PERSIST to save all associated objects.
- Eager loading and Lazy loading; Fetch types: Fetch.LAZY (prefer), Fetch.EAGER
- To retrieve lazy data, a Hibernate session need to be open (connect to the database).
- 📌 Resolve Lazy loading issue (because of loading after closing session)
- Option 1: Call getter method while session is still open [EagerLazyDemo]
- Option 2: Use Hibernate query with HQL [hibernate.query.Query] [FetchJoinDemo]
- Add no-args constructor (required by Hibernate)
- 📌 Add convenience methods for bi-directional one/many-to-many relationship [Instructor]
- @Entity [javax.persistence]
- @Id and @GeneratedValue (prefer GenerationType.IDENTITY)
- @Table: map to table in the database [javax.persistence]
- @Column: map to column of the table
- @OneToOne
[Instructor
/InstructorDetail]
- Uni-directional (use @JoinColumn) and bi-directional (add
mappedBy
to @OneToOne) - @JoinColum: used in the entity class containing the foreign key.
mappedBy
attribute: used in the class entity which does not contain the foreign key.
- Uni-directional (use @JoinColumn) and bi-directional (add
- @OneToMany
[Course
/Review]
- Uni-directional: @JoinColumn used in the class entity which does not contain the foreign key.
- @ManyToMany
[Student
/Course]
fetch
should be FetchType.LAZYcascade
should omit CascadeType.REMOVE- @JoinTable with
joinColumns
andinverseJoinColumns
for each foreign key
- Create a Session Factory including all the entities
- Create a Session
- Start a Transaction
- Perfrom CRUD (save/permit if create or update entities)
- Commit the Transaction
- Handle connection leak issue: catch error and close Session.
- Close the Factory