Intro of JPA, Hibernate, and ORM
I am writing this article to recap my learning on JPA and Hibernate,as recently I am building my project with this framework.
And Hibernate, also a framework to speed up and simplify the process of database connection, is a solution to ORM. Traditionally we use JDBC to implement SQL syntax directly from Java to database, which contains a lot of operation and very time-consuming. With Hibernate, the implementation could be much easier.
ORM
A mapping relationship between objects and table data, so we do not need to operate many complex SQL statements when developing programs. That is to say the advantages are
- Avoid direct operations on the database
- Avoid SQL Injection
But the disadvantage is that if we want to implement more complex SQL operations like join, it will be more difficult to operate.
- Complex SQL operations are less intuitive
- May slow the performance
Hibernate
- Handle basic sql syntax
- Simplify jbdc code
- Provide solutions for ORM
Simply put, Java classes can be mapped to the db data table through the Hibernate framework.
JPA
- A standardized API for ORM
- A spec for
- A set of pre-defined interfaces
- Allow different implementations to be used, and Hibernate is one of them, which is also the default framework of spring boot.
The advantage of using JPA is that it will not be restricted by different implementations and provides flexible code through JPA spec.
Here's how JPA handles the database operations using entityManager.
- to store / retreive data
// save
entityManager.persist(theStudent);
// retrieve
entityManager.find(theStudent);
- to return a list of objects
TypedQuery<Student> theQuery = entityManager.createQuery("from Student", Student.class);
List<Student> students = theQuery.getResultList();
Ok, I think that's my summary for this topic, and I will add more implementation part later.