为 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")
}