Spring 数据 CrudRepository 存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12182809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring data CrudRepository exists
提问by Alexander Camperov
When I extend CrudRepositoryinterface, I have exists(ID)method in my subinteface. I can write findBy<property>methods.
当我扩展CrudRepository接口时,我的子接口中有exists(ID)方法。我可以写findBy<property>方法。
Is it possible somehow to write existBy<property>method that will return boolean. Or to annotate it with @Query(jpa query)so it will return boolean.
是否有可能以某种方式编写existBy<property>将返回的方法boolean。或者用@Query(jpa query)它来注释它,所以它会返回boolean。
I know that I can do select count(*)and return long, but then I will have to do !=0check in my service layer.
我知道我可以做select count(*)并返回long,但是我将不得不!=0检查我的服务层。
回答by Adam
@Oleksandr's answer is correct, but the only way I could get it to work is as follows. I'm using Eclipselink on PostgreSQL.
@Oleksandr 的答案是正确的,但我可以让它工作的唯一方法如下。我在 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);
}
回答by Oleksandr Bondarenko
Actually you can use case expression like this:
实际上,您可以像这样使用 case 表达式:
select case when count(e) > 0 then true else false end from Entity e
where e.property = ?1 -- here go your conditions
回答by Jacob Wallace
As of Spring Data JPA 1.11.0.RELEASE, you can now use existswith query derivation from method names. For example, if you have a Userentity with an emailproperty, you can do this:
从 Spring Data JPA 开始1.11.0.RELEASE,您现在可以使用exists方法名称的查询派生。例如,如果您有一个User带有email属性的实体,您可以这样做:
public interface UserRepository extends JpaRepository<User, Long> {
boolean existsByEmail(String email);
}
回答by Rich Cowin
If you look at the source for org.springframework.data.jpa.repository.support.SimpleJpaRepository.exists(ID)then you will see that it uses a TypedQueryto count records and returns:
如果您查看源代码,org.springframework.data.jpa.repository.support.SimpleJpaRepository.exists(ID)那么您将看到它使用 aTypedQuery来计算记录并返回:
query.getSingleResult() == 1
You can create a query that does something similar for your existsBy(...)methods.
您可以创建一个对您的existsBy(...)方法执行类似操作的查询。

