In this tutorial, we will learn more on Spring Data JPA Repository

JPARepository is an interface in Spring and we will see sample code

JpaRepository Interface methods:

JpaRepository is a Spring Data interface that extends CrudRepository and provides additional functionality for working with JPA (Java Persistence API) based data access. It defines the following additional methods:

  • flush(): Synchronizes the persistence context to the underlying database.
  • saveAndFlush(S entity): Saves a given entity and synchronizes the persistence context to the underlying database.
  • deleteInBatch(Iterable<T> entities): Deletes the given entities in a batch which means it will create a single query to delete all entities.
  • deleteAllInBatch(): Deletes all entities in a batch.
  • getOne(ID id): Retrieves an entity by its id, but unlike findById, it returns a proxy object which will throw an exception if an attempt is made to access the entity’s state before it is accessed in a transaction.
  • findAll(Sort sort): Returns all entities sorted by the given options.
  • findAll(Pageable pageable): Returns a Page of entities meeting the paging restriction provided in the Pageable object.
  • findAll(Example<S> example, Sort sort): Returns all entities matching the given Example and sorted by the given options.
  • findAll(Example<S> example, Pageable pageable): Returns a Page of entities matching the given Example and meeting the paging restriction provided in the Pageable object.
  • count(Example<S> example): Returns the number of entities matching the given Example.
  • exists(Example<S> example): Returns whether an entity matching the given Example exists.

JpaRepository adds more advanced functionality for working with JPA, such as support for sorting and pagination, as well as methods for working with entities based on example.

  1. Create user Entity like shown in below:
@Table(name = "user")
@Entity
public class User {
    @Id
    @Column(name = "user_id")
    private Long userId;
    
    @Column(name="email")
    private String email;

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
    
    
    
}

2. Create UserRepository Interface that should extend JpaRepository and marked with @Repository annotation:


@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

In this example, the UserRepository interface is defined as extending the JpaRepository interface, where User is the entity class and Long is the type of the primary key.

By extending JpaRepository, the UserRepository interface automatically gets a set of methods for performing CRUD operations on the User entity, as well as additional methods for working with JPA-specific features, such as pagination and sorting.

Here is an example of how to use the additional methods provided by JpaRepository

3. Create UserServiceImpl class that should be marked with @Service Annotation:


@Service
public class UserServiceImpl {

	@Autowired
	private UserRepository userRepo;
	
	public void saveUser(User user) {
		userRepo.save(user);

	}

	public User getUser(Long userId) {
		return  userRepo.findOne(userId);

	}
	
	public void deleteUser(Long userId) {
		userRepo.delete(userId);

	}

        public Page<User> getPaginatedUsers(int page, int size){
           Page<User> pagedUsers = userRepo.findAll(PageRequest.of(page, size));
           return pagedUsers ;

        }
       
        public List<User> getUsersByEmail(String email){
           List<User> users = userRepo.findByEmail(email,Sort.by("name").ascending());
           return users;
        }
	
}

In this example, we’re using the @Autowired annotation to automatically wire an instance of the UserRepository into our application, and then using the save, findOne, and delete methods to perform CRUD operations on the repository and findAll, findByEmail method for pagination and sorting.

It’s worth noting that the JpaRepository interface also provides other methods for performing more advanced operations, such as findAll, count, exists, etc. and also it’s methods are build on top of the CrudRepository methods, so it includes all the methods from CrudRepository as well.

Thanks for Reading…