Hibernate Crudepository-选择第一行

Hibernate Crudepository-选择第一行,hibernate,spring-mvc,spring-boot,spring-data-jpa,Hibernate,Spring Mvc,Spring Boot,Spring Data Jpa,我想使用我的Repository类从表中获取第一行。 此时此刻,我被困在这一点上: import com.bodymate.springend.mvc.hiberentity.Trainer; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; public interface TrainerRepository exte

我想使用我的Repository类从表中获取第一行。 此时此刻,我被困在这一点上:

import com.bodymate.springend.mvc.hiberentity.Trainer;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

public interface TrainerRepository extends CrudRepository<Trainer, Integer> {

    @Query("SELECT * FROM trainer LIMIT 1")
    public Trainer getFirst();
}
导入com.bodymate.springend.mvc.hiberentity.Trainer;
导入org.springframework.data.jpa.repository.Query;
导入org.springframework.data.repository.crudepository;
公共接口TrainerRepository扩展了Crudepository{
@查询(“从培训师限制1中选择*)
公共培训师getFirst();
}
编译器不接受关键字“LIMIT”

而且我也不能使用像findFirstBy这样的方法。。。或者先到这里。。。因为所有人都希望有一个选择标准。我认为,通过一个对所有行都适用的选择标准(比如FindFirstBydlessthan(99999))并不是最好的解决方案


如何使用hibernate实现这一点?

创建一个带有可分页参数的帮助器方法,并在指定为默认实现的方法中使用它(或在服务/自定义存储库中单独使用):

@Query(“从培训师t中选择t”)
列表getLimited(可分页页面);
默认可选getFirst(){
return getLimited(第页,共(0,1)页)
.stream()
.findFirst();
}

我发现我必须将用户列表或切片作为返回类型,因此我最终得到了以下定义:
List getFirst(Pageable Pageable)我收到错误:“未能为方法public abstract java.util.List com.bodymate.springend.mvc.repository.TrainerRepository.getFirst(org.springframework.data.domain.Pageable)创建查询!找不到类型培训师的属性getFirst!”哇,很抱歉出现了一个类型。我在回答中更新了代码片段。我猜你删除了你的@Query,它应该留在那里。
@Query("SELECT t FROM trainer t")
List<Trainer> getLimited(Pageable page);

default Optional<Trainer> getFirst() {
  return getLimited(PageRequest.of(0,1))
           .stream()
           .findFirst();
}