Example usage for org.springframework.data.jpa.repository.query QueryUtils getExistsQueryString

List of usage examples for org.springframework.data.jpa.repository.query QueryUtils getExistsQueryString

Introduction

In this page you can find the example usage for org.springframework.data.jpa.repository.query QueryUtils getExistsQueryString.

Prototype

public static String getExistsQueryString(String entityName, String countQueryPlaceHolder,
        Iterable<String> idAttributes) 

Source Link

Document

Returns the query string to execute an exists query for the given id attributes.

Usage

From source file:org.springframework.data.jpa.repository.support.SimpleJpaRepository.java

public boolean exists(ID id) {

    Assert.notNull(id, "The given id must not be null!");

    if (entityInformation.getIdAttribute() == null) {
        return findOne(id) != null;
    }/*w ww  .j a  va2s  .  c  om*/

    String placeholder = provider.getCountQueryPlaceholder();
    String entityName = entityInformation.getEntityName();
    Iterable<String> idAttributeNames = entityInformation.getIdAttributeNames();
    String existsQuery = QueryUtils.getExistsQueryString(entityName, placeholder, idAttributeNames);

    TypedQuery<Long> query = em.createQuery(existsQuery, Long.class);

    if (!entityInformation.hasCompositeId()) {
        query.setParameter(idAttributeNames.iterator().next(), id);
        return query.getSingleResult() == 1L;
    }

    for (String idAttributeName : idAttributeNames) {

        Object idAttributeValue = entityInformation.getCompositeIdAttributeValue(id, idAttributeName);

        boolean complexIdParameterValueDiscovered = idAttributeValue != null && !query
                .getParameter(idAttributeName).getParameterType().isAssignableFrom(idAttributeValue.getClass());

        if (complexIdParameterValueDiscovered) {

            // fall-back to findOne(id) which does the proper mapping for the parameter.
            return findOne(id) != null;
        }

        query.setParameter(idAttributeName, idAttributeValue);
    }

    return query.getSingleResult() == 1L;
}