Based on that transcript "Instructor: In this video, we'll cover the Java code for…
- User
Based on that transcript "Instructor: In this video,
we'll cover the Java code for saving a Java object.
We'll create a sample application,
and these are the features of the application.
We'll write code to create a new student,
read a student, update a student, and also delete a student.
And this is basically a CRUD application.
And we'll start off by creating a new student.
We'll cover some of the other features in following videos.
We'll make use of a student data access object.
The data access object is responsible
for interfacing with the database.
This is a very common design pattern,
data access object or DAO.
Here, we have our application.
It's gonna communicate with this data access object or DAO,
and the DAO will talk to our actual database.
So again, this is kind of like a helper class
for communicating with the database.
Our student data access object will have a number
of methods.
We'll have a save method for saving a student.
We'll have some finder methods for finding by ID,
find all, and find by last name.
We'll also have a method for updating the student.
And then we can also delete and then also perform a delete,
and we'll implement these methods in upcoming videos.
In our scenario,
our data access object needs a JPA EntityManager.
Now the JPA EntityManager's the main component
for saving and retrieving entities.
So we have our student DAO here.
It's gonna make use of an EntityManager
that also has some other supporting components,
and then communicating with the actual database.
Now as far as the other supporting components,
our JPA EntityManager needs a data source.
So the data source
basically defines the database connection information,
and the JPA EntityManager
and the data source are automatically created
by Spring Boot.
Based on information from our Maven POM file,
and also information from our application.properties
such as the URL, user ID, and password,
it'll actually connect to the database,
and then we can autowire or inject the JPA EntityManager
into our student DAO.
And I'll show you the coding for that in a second.
But just to kind of step back here
and kind of look at the architecture diagram here,
we have our data access object
that's gonna make use of an EntityManager.
That'll also make use of a given data source.
And we'll actually inject the EntityManager
into our student DAO.
Let's take a small digression for a second.
Some of you may have done some pre-reading
or you may have seen some online videos,
or read some blog posts.
And you may have read about JpaRepository.
And at this point in the course, you may wonder,
well, what about JpaRepository?
Why are we not using it?
So just a bit of context here.
Spring Data JPA has a JpaRepository interface.
It provides JPA database access with minimal coding.
And here are some of the actual questions
that came from other students in the class
as this course was out and made available.
And here, the first person says,
"Hey, why we have we not simply used JpaRepository
instead of using Entitymanager?"
And the other question here is that,
"I've seen a lot of tutorials online, on YouTube,
and they use JpaRepository.
What's the difference? What's the context?"
And so on.
And then also, when you hear about JpaRepository,
and we talked about EntityManager,
then you're probably wondering,
well, which one do I use?
Like two questions here,
"What's the difference between the two?"
And then also, here, the person at the bottom is saying,
"Which use case should I use?
EntityManager versus JpaRepository, which one runs better?"
And so on.
So I added these slides here.
Once the course was released, I kind of went back,
saw the questions that came in and said,
hey, let's go ahead
and put together some additional slides here
to kind of discuss and address these questions.
So the short answer here is that,
yes, we will use JpaRepository in this course.
We'll cover it later in the course.
And in this course,
I wanna show you various techniques for using JPA.
And in fact, knowing both EntityManager
and JPA will actually help you on future projects.
I've been on previous consulting projects
where we had various team members,
and we had to solve some issues or some issues came up.
And there were some people who only knew
how to use JpaRepository.
They didn't understand all the details behind EntityManager.
So those folks were kind of at a disadvantage.
They really couldn't contribute to the team.
However, developers who knew both EntityManager
and JpaRepository, they could definitely contribute
to the team and add value,
help us resolve issues, and everything else.
So I recommend that you learn both of them.
And again, don't worry,
we'll cover both of these technologies in this course.
Now as far as when to use which, in very simple terms,
if you need low-level control and flexibility,
use EntityManager.
If you want a high level of of abstraction,
then make use of JpaRepository.
Now let's dig into this a bit
and talk more about these use cases here.
Starting here with EntityManager.
EntityManager's useful when you need low-level control
over the database operations,
and you wanna write custom queries.
EntityManager also provides low-level access to JPA,
and allows you to work directly with JPA entities.
And you can use this for a complex queries
that require advanced features
such as native SQL queries or stored procedure calls.
And also, EntityManager is great
when you have customer requirements
that are not easily handled by higher level abstractions.
Now the use case for JpaRepository
is that it provides commonly used CRUD operations
out of the box.
This reduces the amount of code that you need to write.
It also has additional features
such as pagination and sorting.
It can also generate queries based on Java method names.
And you can also create custom queries
using the query annotation.
My recommendation is that the choice
really depends on your application requirements
and developer preference,
but one thing I'd like to point out
is that you can actually use both of these
in the same project.
You wanna leverage the different features of each one.
Now for learning purposes,
I recommend that you start by learning EntityManager first,
then learn JpaRepository.
Because, basically,
this will help you learn the low-level coding
behind the scenes.
And then you can use JpaRepository
for some of the more additional features there.
And again, like I mentioned earlier,
knowing both EntityManager and JpaRepository
will help you on future projects.
Trust me, I've been there.
I've seen it happen real time.
All right, so hopefully that covers
the why JpaRepository, EntityManager discussion.
And now let's kind of move back into the actual videos here,
and let's start writing some code for our student DAO.
" before going to the next video i kinda understand the difference between entitymanager and jparepository but can you shortly reexplain those and also provide some real life examples of when i know which one i should choose?
- Assistant
Certainly! Let's break down the differences between EntityManager and JpaRepository, and explore real-life scenarios to help you understand when to use each one effectively.
1. EntityManager
What is EntityManager?
- EntityManager is a core JPA (Java Persistence API) interface responsible for interacting directly with the persistence context. It provides low-level, fine-grained control over database operations.
Key Features:
- Low-Level Control: Offers detailed operations like persisting, merging, removing, and finding entities.
- Custom Queries: Allows the creation and execution of custom JPQL (Java Persistence Query Language) or native SQL queries.
- Transaction Management: Provides mechanisms to manage transactions manually.
- Suitable for Complex Operations: Ideal for scenarios requiring advanced and customized database interactions.
When to Use EntityManager:
- Complex Queries: When you need to write complex or optimized queries that aren't easily achievable with higher-level abstractions.
- Advanced Mappings: When dealing with intricate entity relationships or mappings that require manual handling.
- Performance Tuning: When you need precise control over caching, fetching strategies, or transaction boundaries for performance optimization.
- Legacy Systems: When integrating with legacy databases or systems that require specific SQL dialects or stored procedures.
Real-Life Example: Imagine you're developing an e-commerce application that needs to generate complex reports combining data from multiple tables with specific performance optimizations. Using EntityManager, you can craft optimized JPQL or native SQL queries tailored to fetch exactly the data you need efficiently.
@PersistenceContext private EntityManager entityManager; public List<OrderReport> generateCustomReport(Date startDate, Date endDate) { String jpql = "SELECT new com.example.OrderReport(o.id, o.total, c.name) " + "FROM Order o JOIN o.customer c " + "WHERE o.date BETWEEN :start AND :end"; return entityManager.createQuery(jpql, OrderReport.class) .setParameter("start", startDate) .setParameter("end", endDate) .getResultList(); }2. JpaRepository
What is JpaRepository?
- JpaRepository is a Spring Data JPA interface that extends CrudRepository and PagingAndSortingRepository. It provides a higher-level abstraction over data access with built-in CRUD operations and additional features.
Key Features:
- CRUD Operations Out-of-the-Box: Methods like
save(),findById(),findAll(),delete(), etc., are readily available. - Derived Query Methods: Ability to generate queries based on method names (e.g.,
findByLastName(String lastName)). - Pagination and Sorting: Built-in support for paging and sorting results.
- Custom Queries with Annotations: Ability to define custom queries using
@Queryannotations when needed. - Less Boilerplate Code: Reduces the amount of boilerplate code required for standard database operations.
When to Use JpaRepository:
- Standard CRUD Needs: When your application primarily requires standard create, read, update, and delete operations.
- Rapid Development: Ideal for quickly setting up data access layers without writing boilerplate code.
- Simple Queries: When queries can be expressed through method names or simple
@Queryannotations. - Pagination and Sorting: When you need built-in support for paginating and sorting data.
Real-Life Example: Suppose you're building a blogging platform where you need to perform standard operations like creating posts, fetching posts by ID or author, updating, and deleting posts. Using JpaRepository makes this straightforward without needing to write custom implementations.
public interface PostRepository extends JpaRepository<Post, Long> { List<Post> findByAuthorLastName(String lastName); @Query("SELECT p FROM Post p WHERE p.title LIKE %:keyword%") List<Post> searchPostsByTitle(@Param("keyword") String keyword); }Choosing Between EntityManager and JpaRepository
Use JpaRepository When:
- You need quick and standard CRUD operations.
- Your queries are simple and can be derived from method names.
- You prefer less boilerplate code and faster development cycles.
- You require built-in pagination and sorting.
Use EntityManager When:
- You need fine-grained control over database interactions.
- You're dealing with complex queries or database operations that cannot be handled by repository methods.
- You need to manage transactions manually or optimize performance with specific strategies.
- You're interacting with legacy systems or databases that require custom SQL.
Combining Both: In many real-world applications, it's common to use JpaRepository for standard operations and EntityManager for specific cases that require advanced handling. Spring Data JPA allows you to integrate both seamlessly within the same project.
Example of Combining Both:
public interface PostRepository extends JpaRepository<Post, Long>, CustomPostRepository { // Standard CRUD and derived queries } public interface CustomPostRepository { List<Post> findPostsWithComplexCriteria(); } public class PostRepositoryImpl implements CustomPostRepository { @PersistenceContext private EntityManager entityManager; @Override public List<Post> findPostsWithComplexCriteria() { // Custom complex query using EntityManager String jpql = "SELECT p FROM Post p WHERE ..."; // complex conditions return entityManager.createQuery(jpql, Post.class).getResultList(); } }In this setup:
- JpaRepository handles standard operations.
- CustomPostRepository with EntityManager manages complex queries.
Summary
- EntityManager offers low-level, fine-grained control suitable for complex and customized database operations.
- JpaRepository provides a higher-level, boilerplate-free approach ideal for standard CRUD operations and simpler queries.
- Both can be used together in the same application to leverage the strengths of each approach based on specific requirements.
Understanding when to use each will enhance your ability to build robust, efficient, and maintainable applications. As you gain experience, you'll develop an intuition for selecting the right tool based on the challenges you encounter in your projects.