為 JPA 管理的實體建立儲存庫

實體

@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
public interface UserRepository extends CrudRepository<User, Long> {
    public User findByUsername(String username);
}

介面中的方法宣告將生成以下 jpql 查詢:

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

或者我們可以定義一個自定義查詢:

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

我們可以輕鬆地為方法宣告新增排序:

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

我們也可以使用內建的分頁支援:

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

然後,服務層(或任何呼叫此方法的人)將 PageRequest 傳遞給該方法:

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