【发布时间】:2019-10-24 22:27:21
【问题描述】:
我有一个表格组件和实体组件。我想从 jpa 查询中选择 id = 1 记录。我可以写“findByIdOne”或“findByIdEqualtoOne”吗?这会给我 id = 1 记录吗?请告诉我,谢谢。
【问题讨论】:
我有一个表格组件和实体组件。我想从 jpa 查询中选择 id = 1 记录。我可以写“findByIdOne”或“findByIdEqualtoOne”吗?这会给我 id = 1 记录吗?请告诉我,谢谢。
【问题讨论】:
【讨论】:
直接编写查询 dsl 你不能,但是 Java 8 有一种使用默认方法的“方法”:
假设您有以下查询:
public interface ComponentRespository extends CrudRepository<Component, Long> {
@Query("select c from Component c where c.id=:id")
Component findById(@Param("id") Long id);
default Component findByIdOne() {
return findById(1L);
}
//eventually
default Component findByIdTwo() {
return findById(2L);
}
}
这样你就可以使用了:
private ComponentRespository componentRepository;
.....
Component componentOne = componentRepository.findByIdOne();
Component componentTwo = componentRepository.findByIdTwo();
【讨论】:
如果不是唯一的,您可以使用Optional<EntityName> findById(long id) 或List<EntityName> findById(long id)。
【讨论】:
如果不是唯一的,您可以使用 Optional<EntityName> findById(long id) 或 List<EntityName> findAllById。
我们有几种选择:
findByIdIs(long id) 或 findByIdEquals(long id)
【讨论】: