Hibernate | JPA CRUD
Hibernate
- Hibernate: A framework for persisting / saving Java objects in a database
- Hibernate handles all of the low-level SQL
- Minimizes the amount of JDBC code you have to develop
- Hibernate provides the Object-to-Relational Mapping (ORM)
Object-To-Relational Mapping (ORM)
JPA
- JPA is Jakarta Persistence API
- Standard API for Object-to-Relational-Mapping (ORM)
- Only a specification
- Defines a set of interfaces
- Requires an implementation to be usable
- Benefits:
- By having a standard API, you are not locked to vendor's implementation
- Maintain portable, flexible code by coding to JPA spec (interfaces)
- Can theoretically switch vendor implementations
- For example, if Vendor ABC stops supporting their product
- You could switch to Vendor XYZ without vendor lock in
- Hibernate is the default implementation in Spring Boot
- JPA term used interchangebly with Hibernate
EntityManager
- In Spring Boot, Hibernate is the default implementation of JPA
EntityManageris main component for creating queries etc …EntityManageris from Jakarta Persistence API (JPA)EntityManageris used for low-level control and flexibility.- Later, we will use
JpaRepositoryfor high-level of abstraction coding.
- Later, we will use
Saving a Java Object with JPA
// create Java object
Student theStudent = new Student("Paul", "Doe", "paul@luv2code.com");
// entityManager is a special JPA helper object
// the persist method is used to save theStudent to database
// the persist method is equivalent to the SQL insert
entityManager.persist(theStudent);
Retrieving a Java Object with JPA
// create Java object
Student theStudent = new Student("Paul", "Doe", "paul@luv2code.com");
// save it to database
entityManager.persist(theStudent);
// now retrieve from database using the primary key
// the find method will query the database for a given id
int theId = 1;
Student myStudent = entityManager.find(Student.class, theId);
Querying for Java Objects
TypedQuery<Student> theQuery = entityManager.createQuery("from Student", Student.class);
// the getResultList method returns a list of Student objects from the database
List<Student> students= theQuery.getResultList();
Hibernate / JPA & JDBC
Hibernate / JPA uses JDBC for all database communications
Creating Spring Boot - Command Line App
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class CruddemoApplication {
//Executed after the Spring Beans have been loaded
public static void main(String[] args) {
SpringApplication.run(CruddemoApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(String[] args) {
//Lambda expression runs your custom code
return runner -> {
System.out.println("Hello world");
};
}
}
Entity Class
Entity Class: Java class that is mapped to a database table
@Entity
- Must have a public or protected no-argument constructor
- The class can have other constructors
Java Annotations
- Map class to database table
//@Entity annotation is needed to map Student to MySQL student database table
@Entity
@Table(name="student")
public class Student {
...
}
- Map fields to database columns
@Entity
@Table(name="student")
public class Student {
//@Column annotation maps id to the id in the database table
@Id
@Column(name="id")
private int id;
//@Column annotation maps firstName to the first_name in the database table
@Column(name="first_name")
private String firstName;
}
@Column
@Columnis optional- If not used, then column name is the same name as java field
tip
Better to specify with
@Columnjust to be safe.
- If not used, then column name is the same name as java field
@Table
@Tableis optional- If not used, then the database table name is same as the class.
tip
Better to specify with
@Tablejust to be safe.
- If not used, then the database table name is same as the class.
Primary Key
- Uniquely identifies each row in a table
- Must be a unique value
- Cannot contain NULL values
Example in MySQL:
CREATE TABLE student (
id int NOT NULL AUTO_INCREMENT,
first_name varchar(45) DEFAULT NULL,
last_name varchar(45) DEFAULT NULL,
email varchar(45) DEFAULT NULL,
PRIMARY KEY (id)
)