14

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
timomeinen
  • 3,101
  • 3
  • 33
  • 46

1 Answers1

9

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.

Oliver Drotbohm
  • 80,157
  • 18
  • 225
  • 211
  • is it still not supported as the documentation implies the opposite. I checked the common docs and jpa and it is contained in both. – Vad1mo Oct 26 '14 at 09:56