Ale*_*rov 28 spring spring-data spring-data-jpa
当我扩展CrudRepository
接口时,我的子接口中有exists(ID)
方法.我可以写findBy<property>
方法.
有可能以某种方式编写existBy<property>
将返回的方法boolean
.或者用@Query(jpa query)
它来注释它将返回boolean
.
我知道我可以做select count(*)
并返回long
,但是我必须!=0
检查我的服务层.
Ada*_*dam 23
@ 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);
}
Run Code Online (Sandbox Code Playgroud)
Ole*_*nko 21
实际上你可以使用这样的case表达式:
select case when count(e) > 0 then true else false end from Entity e
where e.property = ?1 -- here go your conditions
Run Code Online (Sandbox Code Playgroud)
Jac*_*ace 13
从Spring Data JPA开始1.11.0.RELEASE
,您现在可以使用exists
方法名称中的查询派生.例如,如果您有一个User
具有email
属性的实体,则可以执行以下操作:
public interface UserRepository extends JpaRepository<User, Long> {
boolean existsByEmail(String email);
}
Run Code Online (Sandbox Code Playgroud)
如果您查看源代码,org.springframework.data.jpa.repository.support.SimpleJpaRepository.exists(ID)
您会发现它使用 aTypedQuery
来计算记录并返回:
query.getSingleResult() == 1
Run Code Online (Sandbox Code Playgroud)
您可以创建一个查询来为您的方法执行类似的操作existsBy(...)
。
归档时间: |
|
查看次数: |
35408 次 |
最近记录: |