03 Spring Boot Hibernate Jpa Crud
03 Spring Boot Hibernate Jpa Crud
© luv2code LLC
Topics
• What is Hibernate?
• Benefits of Hibernate
• What is JPA?
• Benefits of JPA
• Code Snippets
• www.hibernate.org/orm
Your Hibernate
Java
App
Hibernate
JPA Spec
Hibernate EclipseLink
www.luv2code.com/jpa-vendors
My Biz
App
JPA Spec
EclipseLink
Hibernate
// save it to database
entityManager.persist(theStudent);
Special JPA helper object The data will be stored in the database
SQL insert
// save it to database
entityManager.persist(theStudent);
// now retrieve from database using the primary key
int theId = 1;
Student myStudent = entityManager.find(Student.class, theId);
• Create objects
• Read objects Your JPA
Java Hibernate
App
• Update objects
• Delete objects
© luv2code LLC
How does Hibernate / JPA
relate to JDBC?
JPA
Your JDBC
Hibernate
Java
App
© luv2code LLC
MySQL Database
• In this course, we will use the MySQL Database
• MySQL Workbench
• Others …
© luv2code LLC
Two Database Scripts
1. Folder: 00-starter-sql-scripts
01-create-user.sql
02-student-tracker.sql
password: springstudent
© luv2code LLC
Automatic Data Source Configuration
• In Spring Boot, Hibernate is the default implementation of JPA
• You can then inject these into your app, for example your DAO
• Add dependencies
spring.datasource.url=jdbc:mysql://localhost:3306/student_tracker
spring.datasource.username=springstudent
spring.datasource.password=springstudent
@Bean
public CommandLineRunner commandLineRunner(String[] args) {
Lambda return runner -> {
expression System.out.println("Hello world"); Add our
}; custom code
}
}
© luv2code LLC
JPA Dev Process - To Do List
1. Annotate Java Class
• Going forward in this course, I will simply use the term: JPA
Entity Class
JPA
@Entity
@Table(name="student")
public class Student {
...
Java Class Database Table
}
@Id
@Column(name="id")
private int id; Java Class Database Table
@Column(name="first_name")
private String firstName;
…
}
• If not specified, the column name is the same name as Java field
• If you refactor the Java code, then it will not match existing database columns
• This is a breaking change and you will need to update database column
Primary Key
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
…
}
Name Description
• Create implementation of
org.hibernate.id.IdentifierGenerator
© luv2code LLC
Sample App Features
• Create a new Student
• Read a Student
Cruddemo Student
App DAO
Methods
save(…)
findById(…)
findAll()
findByLastName(…)
update(…)
delete(…)
deleteAll()
Student Entity
…
DAO Manager
• JPA Entity Manager and Data Source are automatically created by Spring Boot
• Based on the file: application.properties (JDBC URL, user id, password, etc …)
• We can autowire/inject the JPA Entity Manager into our Student DAO
Student Entity
Data Source
DAO Manager
Student Entity
Data Source
DAO Manager
import com.luv2code.cruddemo.entity.Student;
@Override
public void save(Student theStudent) {
entityManager.persist(theStudent); Save the
} Java object
}
@Autowired
public StudentDAOImpl(EntityManager theEntityManager) {
entityManager = theEntityManager;
}
@Component
@RestController @Repository …
• thanks to component-scanning
@Override
@Transactional
public void save(Student theStudent) {
entityManager.persist(theStudent);
}
@Bean
public CommandLineRunner commandLineRunner(StudentDAO studentDAO) {
return runner -> {
createStudent(studentDAO);
}
© luv2code LLC
JPA CRUD Apps
• Create objects
• Read objects
• Update objects
• Delete objects
import com.luv2code.cruddemo.entity.Student;
@Override
public Student findById(Integer id) {
return entityManager.find(Student.class, id); If not found,
} returns null
}
Entity class Primary key
@Bean
public CommandLineRunner commandLineRunner(StudentDAO studentDAO) {
return runner -> {
readStudent(studentDAO);
};
} private void readStudent(StudentDAO studentDAO) {
// create a student object
… System.out.println("Creating new student object...");
Student tempStudent = new Student("Daffy", "Duck", "[email protected]");
© luv2code LLC
JPA CRUD Apps
• Create objects
• Read objects
• Update objects
• Delete objects
theQuery.setParameter("theData", theLastName);
return theQuery.getResultList();
} Think of this as a placeholder
that is filled in later
import com.luv2code.cruddemo.entity.Student;
import java.util.List;
List<Student> findAll();
@Override
public List<Student> findAll() {
TypedQuery<Student> theQuery = entityManager.createQuery(“FROM Student", Student.class);
return theQuery.getResultList();
}
}
Name of JPA Entity
@Bean
public CommandLineRunner commandLineRunner(StudentDAO studentDAO) {
return runner -> {
queryForStudents(studentDAO);
};
}
© luv2code LLC
JPA CRUD Apps
• Create objects
• Read objects
• Update objects
• Delete objects
import com.luv2code.cruddemo.entity.Student;
@Bean
public CommandLineRunner commandLineRunner(StudentDAO studentDAO) {
return runner -> {
updateStudent(studentDAO);
};
} private void updateStudent(StudentDAO studentDAO) {
System.out.println("Updating student...");
© luv2code LLC
JPA CRUD Apps
• Create objects
• Read objects
• Update objects
• Delete objects
import com.luv2code.cruddemo.entity.Student;
@Bean
public CommandLineRunner commandLineRunner(StudentDAO studentDAO) {
return runner -> {
deleteStudent(studentDAO);
};
}
private void deleteStudent(StudentDAO studentDAO) {
… // delete the student
int studentId = 3;
studentDAO.delete(studentId);
}
© luv2code LLC
Create database tables: student
• Previously, we created database tables by running a SQL script
Java
Code
spring.jpa.hibernate.ddl-auto=create
• When you run your app, JPA/Hibernate will drop tables then create them
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="email")
private String email;
…
// constructors, getters / setters
}
spring.jpa.hibernate.ddl-auto=create
• Database tables are dropped first and then created from scratch
Note:
When database tables are dropped, all data is lost
• Instead for Production, you should have DBAs run SQL scripts
• You can VERY easily drop PRODUCTION data if you are not careful
• Corporate DBAs prefer SQL scripts for governance and code review
• The SQL scripts can be customized and fine-tuned for complex database designs
• Can also work with schema migration tools such as Liquibase and Flyway