Post

Jpa (1)

To tell you a little bit about myself, I’m currently partaking in an educational program called SSAFY (Samsung Software Academy For Youth) after graduating with a Bachelor’s degree. This is my 2nd semester here and I have to carry out multiple team projects in this period. For my first project, I was assigned the role of Back-end, wherein I was to program using Spring Boot. For this project, my team decided to use JPA, Java Persistence API, as the ORM. However, since this was a new technology to me, Hence, I decided to start a research on JPA, this week,

JPA vs MyBatis

In the previous projects, I utilized myBatis for the interaction with DB. However it seems that many developers favor JPA over myBatis, as seen on the chart below. trend

So what is JPA, how is it different from myBatis, and why would one use it? I want to start with a simple explanation on JPA. As it can be hinted by its name, JPA is an API, and it defines the method the application will interact with the database. It is the standard ORM (Object-Relational Mapping) that is used in Java, which seeks to connect Java objects with the data in DB. It facilitates the process of manipulating the database within Java environment, and therefore is considered a very essential component. Java Appliaction

Okay, I now know what JPA does. So, why would one use it over myBatis? Firstly, let’s look at the differences between the two. MyBatis requires its user to write SQL queries, and uses XML or annotations for data mapping. However, JPA supports mapping between objects and the database, and instead of using SQL, it uses alternative methods; there are means such as JPA methods, an object-oriented query language called JPQL, or query DSL. Lets’ list some advantages you gain from using JPA.

  1. Reduction of Written Code (Because a single JPA method can be transcribed into multiple SQL statements)
  2. Better Readability
  3. Malleability (Suitable for larger projects where flexibility and expandability)
  4. Compatibility with different DBMS (Don’t have to change the code even when DBMS is changed)

However, one must also be aware of the fact that we are sending queries through methods, and that means there can be work to be done–possibly longer time taken.

JPA method vs JPQL vs Query DSL

As aforementioned, there were three methods of achieving query result while using JPA. Firstly one can use a JPA method. For each of the CRUD operations, there is a JPA method.

  • INSERT -> persist
  • SELECT -> find
  • UPDATE -> merge
  • DELETE -> remove

Example: jpa.persist(school);

One can utilize these methods to carry out simple SQL queries, all in Java format. This facilitates the backend programmer’s work, since they don’t have to write anything in queries. However, in spite of this advantage, JPA methods are rigid and elementary at best, and therefore in order to carry out a more high-level instruction, we must use JPQL or Query DSL. In order to implement JPQL, one can choose between two ways.

  • Use EntityManager Class
1
2
3
4
5
6
@Autowired
EntityManager em;
...
TypedQuery<School> tq = em.createQuery("select t from Teacher t where t.FirstName = :firstName and t.LastName = :lastName", Teacher.class);
tq.setParameter("firstName", "Emily");
tq.setParameter("lastName", "Henderson");
  • Use Repository Interface
    1
    2
    3
    4
    
    public interface PersonRepository extends JpaRepository<Person, Long>{`
     @Query("select t from Teacher t where t.firstName = :firstName and t.lastName = :lastName")
     Teacher findTeacher(@Param("firstName") String firstName, @Param("lastName") String lastName);
    }
    

As you have noticed, the query must be written in a String format. This greatly increases the likelihood of errors popping up at runtime stage since it can’t be detected during compilation.

How about query DSL?

1
2
3
4
5
6
7
8
JPAQueryFactory jpaqf = new JPAQueryFactory(em);
...
List<Teacher> teacherList = jpaqf.selectFrom(teacher)
				.where(teacher.firstName.eq(firstName)
				.and(teacher
				.lastName
				.eq(lastName))
				.fetch();

We can see that its not in a string format, making error-checking much easier. query DSL can be seen as an improvement over JSQL since it only utilizes static data format. At first sight, it might seem hard to decipher, but in the long run, this method will be an improvement over the former.

Conclusion

So, today I tried my best to describe what I learned about JPA–what it is, why one would use it, and the means to implement it. I wanted to also cover the topic of hibernate here, but gave up from the fear that the post will be way- tooo- long. Anyways that was it for today’s post…

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.