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”

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

    @Id
    @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.

Distinguished Engineer Java, PHP, Spring, Mysql
Posts created 5

One thought 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!

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

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