Implementation of Spring Data JPA repositories

With the domain model implemented successfully, the JpaRepository for those can be implemented using Spring Data JPA. The specialty here is that there is no need to implement anything. Just writing an interface that extends from the JpaRepository interface will be sufficient to expose methods to find one, find all, save, delete, and so on. The following code shows CommentRepository:

public interface CommentRepository extends JpaRepository<Comment, Long> {

@Query("SELECT c FROM Comment c WHERE year(c.createdDate) = ?1 AND
month(c.createdDate) = ?2 AND
day(c.createdDate) = ?3"
)
List<Comment> findByCreatedYearAndMonthAndDay(int year, int month,
int
day);

}

Since a list of comments for a specific date needs to retrieved to be shown in the frontend, a custom method with a @Query annotation is added to the CommentRepository interface. This annotation is responsible for using a database-independent SQL query to filter out data from the database.

The following code shows UserRepository:

public interface UserRepository extends JpaRepository<User, Long> {

User findByUsername(String username);
}

In the preceding code, there is a method named findByUsername where username is a property of User class. In this case, an @Query annotation is not required, as the naming of the method will be used to create the filter. There are more things that can be done using Spring Data JPA; see in the official documentation at https://docs.spring.io/spring-data/jpa/docs/current/reference/html/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.62.122