Skip to content

enginooby-practice/hibernate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

46 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Practice topics

Configuration

Concepts

  • 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]

Entity Class

  • 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.
  • @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.LAZY
    • cascade should omit CascadeType.REMOVE
    • @JoinTable with joinColumns and inverseJoinColumns for each foreign key

App Flow

[CreateDemo]

  1. Create a Session Factory including all the entities
  2. Create a Session
  3. Start a Transaction
  4. Perfrom CRUD (save/permit if create or update entities)
  5. Commit the Transaction
  6. Handle connection leak issue: catch error and close Session.
  7. Close the Factory