Advertisement

Sri Lanka's First and Only Platform for Luxury Houses and Apartment for Sale, Rent

Tuesday, January 10, 2017

Spring data JPA with dynamic where clause

It may be a Common Use Case where you need to dynamically submit a WHERE Clause to a Spring Data Repository to get an Entity instead of Writing findBy* methods or @Query annotated methods. You can do the following;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;

import java.io.Serializable;
import java.util.Map;

/**
 * Created by shazi on 1/11/2017.
 */
@NoRepositoryBean
public interface IBaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T> {

    T findOne(String filter, Map<String, Object> params);

}
And Implement it as follows.
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.Map;

/**
 * Created by shazi on 1/11/2017.
 */
public class BaseRepositoryImpl<T, ID extends Serializable>
        extends SimpleJpaRepository<T, ID> implements IBaseRepository<T, ID> {

    private final EntityManager entityManager;

    private final JpaEntityInformation entityInformation;

    public BaseRepositoryImpl(JpaEntityInformation entityInformation,
                            EntityManager entityManager) {
        super(entityInformation, entityManager);

        // Keep the EntityManager around to used from the newly introduced methods.
        this.entityManager = entityManager;
        this.entityInformation = entityInformation;
    }

    @Override
    public T findOne(String filter, Map<String, Object> params) {
        final String jpql = "FROM " + entityInformation.getEntityName() + " WHERE " + filter;
        Query query = entityManager.createQuery(jpql);
        for (Map.Entry<String, Object> value:params.entrySet()) {
            query.setParameter(value.getKey(), value.getValue());
        }
        return (T) query.getSingleResult();
    }
}
And configure it as follows
@Configuration
@EnableJpaRepositories(repositoryBaseClass = BaseRepositoryImpl.class)
@EnableTransactionManagement
public class RepoConfig {
or in XML
<repositories base-class="….BaseRepositoryImpl" />
Finally you can use it as follows;
User found = userRepository.findOne("name = :name", Collections.singletonMap("name", "name"));
But you have to make sure that your query WHERE is such that the Query will always return 1 result only.

References