I got a query like this, not able to make sense of this, what this query is doing!!
SimpleJpaRepository<SomeEntity, Long> repo = this.repoFactory.createJpaRepository(SomeEntity.class, Boolean.FALSE);
Optional<SomeEntity> someKeyOpt = repo.findOne((root, query, cb) -> {
return cb.and(cb.equal(root.get("active"), Boolean.TRUE));
});
if (someKeyOpt.isPresent()) {
return someKeyOpt.get().getPublicKey();
}
return null;
What is this lambda expression doing? Why are we even having it here? What is this root? And what is this cb thing?
(root, query, cb) -> {
return cb.and(cb.equal(root.get("active"), Boolean.TRUE));
}
This is an example of Spring Data JPA Criteria Query. And we are using SimpleJpaRepository, which is a concrete class implementing JpaRepository interface, among other ones.
this.repoFactory.createJpaRepository(SomeEntity.class, Boolean.FALSE);
This line is calling on repoFactory, some custom Factory implemenation, and calling createJpaRepository on it. Notice its, passing SomeEntity.class, this help to create a repository on SomeEntity.class, and also we are passing Boolean.FALSE, this seems to be disabling caching or some such related parameter value.
Now let's come to the Lambda,
root : In Criteria Query, the specifies the Entity, from which the data will be selected.
cb : It's the criteria builder here.
So the query is actually returning, those rows in SomeEntity table which have the active value column in the row set as True.
On getting one of that, it's returning the publicKey.
If there is none, a null is being returned.