Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the exists keyword in Spring Data to check for the existence of an entity?

Tags:

spring-data

How do I use the 'exists' keyword in Spring Data in a query method?

I would like to have a method like this:

public interface ProfileRepository extends JpaRepository<Profile, Long> {
  boolean existsByAttribute(String attribute);
}

where Attribute is a field of the Profile.

A workaround would be to use a custom-implementation. But the appendix defines exists as keyword. Could someone give me an example how to use this keyword?

like image 933
timomeinen Avatar asked Jan 07 '13 16:01

timomeinen


People also ask

What is difference between Jparepository and Crudrepository?

Crud Repository is the base interface and it acts as a marker interface. JPA also provides some extra methods related to JPA such as delete records in batch and flushing data directly to a database. It provides only CRUD functions like findOne, saves, etc. JPA repository also extends the PagingAndSorting repository.

How do you check if JPA save was successful?

I want to know how to check if save was success or not? You can check it by using if (person != null) and return a response. The documentation says entity will never be null.

What is @query in spring?

In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm. xml file.


1 Answers

Documented keywords are intended to be used in combination with a property reference. Thus, the semantics of EXISTS in this case are that it checks whether the property exists. Note, that the part of the documentation is pulled it from Spring Data Commons and the keyword being listed there doesn't mean it's supported in Spring Data JPA (indicated in the first paragraph of the section you linked). Exists is not supported by Spring Data JPA as it only makes sense in MongoDB for example as there's a difference between a field not present entirely and the field available with a logically null value.

So what you're looking for seems to be around the (Is)Null keyword with the current limitation that it would return objects and you'd have to check the returned list for content. There's a ticket to add support for projections for derived query methods which you might wanna follow for further progress.

like image 118
Oliver Drotbohm Avatar answered Sep 28 '22 06:09

Oliver Drotbohm