spring-data-jpa Repositories Creating a repository for a JPA-managed entity


Entity class

@Table(name = "USER")
public class User {
    @Column(name = "ID")
    private Long id;
    @Column(name = "USERNAME")
    private String username;
    private Organization organization;

Repository interface

public interface UserRepository extends CrudRepository<User, Long> {
    public User findByUsername(String username);

The method declaration in the interface will generate the following jpql query:

select u from User u where u.username = :username

alternatively we can define a custom query:

@Query("select u from User u where u.username = :username")
public User findByUsername(@Param("username") String username) 

we can easily add sorting to the method declaration:

public interface UserRepository extends PagingAndSortingRepository<User, Long> {
    public User findByUsernameOrderByUsernameAsc(String username);

we can also use in-built pagination support:

public Page<User> findByOrganizationPaged(Organization organization, Pageable pageable);

the service layer (or whoever calls this method) will then pass a PageRequest to the method:

public Page<User> getByOrganizationPagedOrderByUsername(Organization organization, int page, int size, String direction){
    return userRepository.findByOrganizationPaged(organization, new PageRequest(page, size, Direction.valueOf(direction),