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


Example

Entity class

@Entity
@Table(name = "USER")
public class User {
    @Id
    @Column(name = "ID")
    private Long id;
    
    @Column(name = "USERNAME")
    private String username;
    
    @ManyToOne
    @JoinColumn("ORGANIZATION_ID")
    private Organization organization;
}

Repository interface

@Repository
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),
                "username")
}