-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Closed as not planned
Closed as not planned
Copy link
Description
Hello.
I am studying Spring Data JPA and I have a question about the generated query when executing the existsById().
Despite of the Id is a unique column, is there a specific reason for using a count(*) query?
Out of curiosity, I tested a method like existsByName() for a regular column and found that it generates a query using LIMIT, which actually performed better.
I am curious why a count(*) query is used when checking existsById(ID id) in SimpleJpaRepository.
// SimpleJpaRepository
public boolean existsById(ID id) {
Assert.notNull(id, "The given id must not be null");
if (this.entityInformation.getIdAttribute() == null) {
return this.findById(id).isPresent();
} else {
String placeholder = this.provider.getCountQueryPlaceholder();
String entityName = this.entityInformation.getEntityName();
Iterable<String> idAttributeNames = this.entityInformation.getIdAttributeNames();
String existsQuery = QueryUtils.getExistsQueryString(entityName, placeholder, idAttributeNames);
...// PersistenceProvider
public String getCountQueryPlaceholder() {
return "x";
}// QueryUtils
public static String getExistsQueryString(String entityName, String countQueryPlaceHolder, Iterable<String> idAttributes) {
String whereClause = (String)Streamable.of(idAttributes).stream().map((idAttribute) -> {
return String.format("%s.%s = :%s", "x", idAttribute, idAttribute);
}).collect(Collectors.joining(" AND ", " WHERE ", ""));
String var10000 = String.format("select count(%s) from %s x", countQueryPlaceHolder, entityName);
return var10000 + whereClause;
}From my perspective, it seems that the query generation method only for existsById() could be defined within QueryUtils.
I am curious about this matter.
I apologize if my poor English skills made it difficult for you to read.
Metadata
Metadata
Assignees
Labels
No labels