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
3.2 define your own CUSTOM generation strategy
create subclass of org.hibernate.id.SequenceGenerator
Override the method: public Serializable generate(...)
3.3 changing the index
SQL
3.4 retrieving an object
3.5 Querying Object
hibernate 5.2+
e.g.
e.g.
3.6 Updating Objects
3.7 Delete a Student
e.g.1
e.g.2
4. Advanced Mapping
One-to-One
Many-to-One, One-to-Many
Many-to-Many
Uni-Directional: One -to- One
4.1 Primary Key and Foreign Key
Primary key: identify a unique row in a table
Foreign Key:
Link tables together
a field in one table that refers to primary key in another table
4.2 Cascade
You can cascade operations
Apply the same operation to related entities
By default, no operations are cascaded.
e.g
If we delete an instructor, we should also delete their instuctor_detail
This is known as "CASCADE DELETE". It depends on the use case.
4.3 Eager vs Lazy Loading
Eager will retrieve everything
Lazy will retrieve on request
4.4 Create Instructor class - @OneToOne
5 Entity Lifecycle
Operations
Description
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 instances 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
5.1 @OneToOne
5.1.1 - Cascade Type
Persist, Remove, Refresh, Detach, Merge, All.
configure cascade Type
configure cascade Type
5.1.2 @OneToOne Bi-Directional
mappedBy tells Hibernate
Look at the instructorDetail property in the Instructor class
Use information from the Instructor class @JoinColumn
To help find associated instructor
5.1.3 Code Refactoring Add Exception Handling
5.1.4 Only delete InstructorDetail keep the Instructor
remove the associated object reference
break bi-directional link
cascade: Do not apply cascading deletes!
5.2 @OneToMany
An instructor can have many courses
Bi-directional
Many-to-One Mapping
Many courses can have one instructor
Inverse / opposite of One-to-Many
Real-World Project Requirement
If you delete an instructor, DO NOT delete the courses
If you delete a course, DO NOT delete the instrucrot
When add support for Cascading:
Do not apply cascading deletes!
5.2.1 @JoinColumn & @mappedBy
@JoinColumn
A Join Column in JPA is a column in the owner entity that refers to a key (usually a primary key) in the non-owner or inverse entity. The first thing that comes to mind after reading the above line is that JoinColumns are nothing but a Foreign Key Columns. And it is indeed the case. JPA calls them Join Columns, possibly because they are more verbose in what their actual role is, to join the two entities using a common column.
Another thing to notice above is that we have used the terms owner and non-owner entities. For easy rememberability, the entity that has a join column is always the owning entity.
@mappedBy
The field that owns the relationship. Required unless the relationship is unidirectional.
//create session factory
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
//create session
Session session = factory.getCurrentSession();
try{
//start a transaction
session.beginTransaction();
//query students
List<Student> theStudents= session.createQuery("from Student").list();
//display the students
for(Student tempStudent:theStudents){
System.out.println(tempStudent);
}
//commit transaction
session.getTransaction().commit();
System.out.println("Done!");
}finally{
factory.close();
}
List<Student> theStudents= session.createQuery("from Student").list();
//display the students
displayStudents(theStudents);
//query students: last name = "poter"
theStudents = session.createQuery("from Student s where s.lastName='Potter' OR s.firstName='Daffy'").list();
System.out.println("Student with last name potter: ");
displayStudents(theStudents);
try{
int studentId = 1;
session=factory.getCurrentSession();
session.beginTransaction();
System.out.println("\n Getting student with id: "+ studentId);
Student myStudent = session.get(Student.class, studentId);
//commit transaction
System.out.println("Get complete: "+ myStudent);
//update email for all student
session.createQuery("update Student set email='foo@gmail.com'").executeUpdate();
session.getTransaction().commit();
System.out.println("Done!");
}finally{
factory.close();
}
Student myStudent = session.gett(Student.class, studentId);
//delete the student
session.delete(myStudent);
//commit the transaction
session.getTransaction().commit();
session.createQuery("delete from Student where id=2").executeUpdate();//executeUpdate() is used for updates or delete
@Entity
@Table(name="instructor")
public class Instructor{
...
@OneToOne
@JoinColumn(name="instructor_detail_id")
private InstructorDetail instructorDetail;
...
}
public class InstructorDetail{
...
@OneToOne(mappedBy="instructorDetail", cascade={CascadeType.DETACH, CascadeType.MERGE})
private Instructor instructor;
//main app
System.out.println("Deleting tempInstructorDetail.");
//remove the associated object reference
//break bi-directional link
tempInstructorDetail.getInstructor().setInstructorDetail(null);//break link when cascade=CascadeType.ALL
session.delete(tempInstructorDetail);//delete
@Entity
@Table(name="instructor")
public class Instructor{
...
@OneToMany(mappedBy="instructor", cascade={CascadeType.PERSIST, CascadeType.MERGE...})//Refers to "instructor" property in "Course" class
private List<Course> courses;
@OneToOne(mappedBy="instructorDetail")//instructor is the owner of the relationship.
private Instructor instructor;