当我扩展CrudRepository
接口时,我在我的子接口中有exists(ID)
方法。我可以写findBy<property>
方法。弹簧数据CrudRepository存在
是否有可能以某种方式编写existBy<property>
方法将返回boolean
。或者用@Query(jpa query)
对其进行注释,以便返回boolean
。
我知道我可以做select count(*)
并返回long
,但是接下来我将不得不在!=0
检查我的服务层。
当我扩展CrudRepository
接口时,我在我的子接口中有exists(ID)
方法。我可以写findBy<property>
方法。弹簧数据CrudRepository存在
是否有可能以某种方式编写existBy<property>
方法将返回boolean
。或者用@Query(jpa query)
对其进行注释,以便返回boolean
。
我知道我可以做select count(*)
并返回long
,但是接下来我将不得不在!=0
检查我的服务层。
如果你看看来源为org.springframework.data.jpa.repository.support.SimpleJpaRepository.exists(ID)
,那么你将看到它使用了一个TypedQuery
数记录和回报:
query.getSingleResult() == 1
您可以创建一个查询,确实为您existsBy(...)
方法类似。
是的,我查看了源代码。那时我必须实现我的Dao界面。当我不需要这样做时,我正在寻找解决方案=) –
其实你可以使用的情况下表达这样的:
select case when count(e) > 0 then true else false end from Entity e
where e.property = ?1 -- here go your conditions
@奥列克的答案是正确的,但我可以得到它的工作的唯一方法是如下。我在PostgreSQL上使用Eclipselink。
public interface UserRepository extends JpaRepository<User, Long>
{
@Query("SELECT CASE WHEN COUNT(u) > 0 THEN 'true' ELSE 'false' END FROM User u WHERE u.username = ?1")
public Boolean existsByUsername(String username);
}
这是Spring Data在v1.11.0之前的一个很好的解决方法。 @ alexander-camperov如果你同意它解决了你的问题,请接受这个答案。 – naXa
由于Spring数据JPA 1.11.0.RELEASE
的,你现在可以使用exists
与方法名称查询推导。举例来说,如果你有一个User
实体与email
属性,你可以这样做:
public interface UserRepository extends JpaRepository<User, Long> {
boolean existsByEmail(String email);
}
现在看来'existsBy'已经被破坏了:C https://jira.spring.io/browse/DATAJPA-851 –
“但我将不得不这样做= 0查一下我的服务层!”。也使用存在,而不是计数将更有效的分贝查询 – WeGa