Spring Data JPA : Don’t need to write SQL queries.

If you are not aware of spring data JPA this article is for you. Even if you are aware still you can read complex cases that can help you.

Note that Spring Data is a collection of many modules. You may find these here https://spring.io/projects/spring-data . Spring Data JPA is a part of Spring data.

Spring Data JPA made data access really easy. Even you don’t need to write queries. Let us understand this by a simple example.

Suppose you have an entity “Conversation”

@Table(name = "conversions")
public class Conversation extends BaseEntity {

    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(updatable = false, name = "id", unique = true)
    private Long id;

    @Column(updatable = false, name = "public_id", unique = true)
    private Long publicId;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="from_id",  referencedColumnName="id")
    private User from;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="to_id",  referencedColumnName="id")
    private User to;


The conversation entity has two associations with the User entity “from_id” and “to_id”. With Spring Data JPA we can write methods that can generate queries underline.

You just need to create an interface that extends JpaRepository. You just have to declare

public interface ConversationRepository extends JpaRepository<Conversation,Long> {
//This method generates : select * from Conversation where publicId=1;
	Conversation findByPublicId(Long publicId);
//This methods join with user table and get the records 
List<Conversation> findByPublicIdAndTo_Id(Long publicId,Long toId);

// This will have two joins with user table for fields From and To
List<Conversation> findByFrom_IdOrTo_Id(Long fromId,Long toId);

The first method is simple if get the records by pubicId.
The Second one finds the record with publicId also do an AND with To user id.
Thrid case a bit complex, where you can pull records where from from_id=? OR to_id=?

If you have proper associations within entities you can write methods that can generate complex queries having joins.

Please share this post:
Distinguished Engineer Java, PHP, Spring, Mysql
Posts created 11

2 thoughts on “Spring Data JPA : Don’t need to write SQL queries.

  1. Have you ever considered about adding a little bit more than just your articles? I mean, what you say is fundamental and all. However think about if you added some great graphics or videos to give your posts more, “pop”! Your content is excellent but with images and videos, this blog could undeniably be one of the very best in its field. Terrific blog!

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: