DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Projections/DTOs in Spring Data R2DBC
  • Testcontainers With Kotlin and Spring Data R2DBC
  • How to Store Text in PostgreSQL: Tips, Tricks, and Traps

Trending

  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Navigating Double and Triple Extortion Tactics
  1. DZone
  2. Data Engineering
  3. Databases
  4. Adding Hibernate Entity Level Filtering feature to Spring Data JPA Repository

Adding Hibernate Entity Level Filtering feature to Spring Data JPA Repository

By 
Boris Lam user avatar
Boris Lam
·
Aug. 24, 12 · Interview
Likes (1)
Comment
Save
Tweet
Share
56.3K Views

Join the DZone community and get the full member experience.

Join For Free

Original Article: http://borislam.blogspot.hk/2012/07/adding-hibernate-entity-level-filter.html

Those who have used data filtering features of hibernate should know that it is very powerful. You could define a set of filtering criteria to an entity class or a collection. Spring data JPA is a very handy library but it does not have fitering features. In this post, I will demonstarte how to add the hibernate filter features at entity level. You can use this features when you are using Hibernate Entity Manager. We can just define annotation in your repositoy interface to enable this features.

 Step 1. Define filter at entity level as usual. Just use hibernate @FilterDef annotation

@Entity
@Table(name = "STUDENT")
@FilterDef(name="filterBySchoolAndClass", parameters={@ParamDef(name="school", type="string"),@ParamDef(name="class", type="integer")})
public class Student extends GenericEntity implements Serializable {
  // add your properties ...
}


 Step2. Define two custom annotations. 

These two annotations are to be used in your repository interfaces. You could apply the hibernate filter defined in step 1 to specific query through these annotations.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EntityFilter {
 FilterQuery[] filterQueries() default  {};
}


@Retention(RetentionPolicy.RUNTIME)
public @interface FilterQuery {
 String name()  default "";
 String jpql()  default "";
}


 Step3. Add a method to your Spring data JPA base repository. 

This method will read the annotation you defined (i.e. @FilterQuery) and apply hibernate filter to the query by just simply unwrap the EntityManager. You could specify the parameter in your hibernate filter and also the parameter in you query in this method.

If you do not know how to add custom method to your Spring data JPA base repository, please see my previous article for how to customize your Spring data JPA base repository for detail. You can see in previous article that I intentionally expose the repository interface (i.e. the springDataRepositoryInterface property) in the GenericRepositoryImpl. This small tricks enable me to access the annotation in the repository interface easily.

public List<T> doQueryWithFilter( String filterName, String filterQueryName, Map inFilterParams, Map inQueryParams){
    if (GenericRepository.class.isAssignableFrom(getSpringDataRepositoryInterface())) {
       Annotation entityFilterAnn = getSpringDataRepositoryInterface().getAnnotation(EntityFilter.class);
       if(entityFilterAnn != null){
        EntityFilter entityFilter = (EntityFilter)entityFilterAnn;
        FilterQuery[] filterQuerys  = entityFilter.filterQueries() ;
        for (FilterQuery fQuery : filterQuerys) { 
         if (StringUtils.equals(filterQueryName, fQuery.name())) {
          String jpql = fQuery.jpql();
          Filter filter = em.unwrap(Session.class).enableFilter(filterName);
           
          //set filter parameter
          for (Object key: inFilterParams.keySet()) {
           String filterParamName = key.toString();
           Object filterParamValue = inFilterParams.get(key);
           filter.setParameter(filterParamName, filterParamValue);
                }
           
          //set query parameter
          Query query= em.createQuery(jpql);
          for (Object key: inQueryParams.keySet()) {
           String queryParamName = key.toString();
           Object queryParamValue = inQueryParams.get(key);
           query.setParameter(queryParamName, queryParamValue);
                }
          return query.getResultList();
         }
        }
       }
      }
     }
     return null;
    }
 

 Last Step: example usage

In your repositry, define which query you would like to apply hibernate filter through your @EntityFilter and @FilterQuery annotation.
@EntityFilter (
 filterQueries = {
   @FilterQuery(name="query1", 
       jpql="SELECT s FROM Student LEFT JOIN FETCH s.Subject where s.subject = :subject" ),
   @FilterQuery(name="query2", 
       jpql="SELECT s FROM Student LEFT JOIN s.TeacherSubject where s.teacher =  :teacher")       
 }
)
public interface StudentRepository extends GenericRepository<Student, Long> {
}

 

In your service or business class that inject your repository, you could just simply call the doQueryWithFilter() method to enable the filtering function. 

@Service
public class StudentService {
 
 @Inject
 private StudentRepository studentRepository;
 
 public List<Student> searchStudent( String subject, String school, String class) {
    
  List<Student> studentList;
 
  // Prepare parameters for query filter
  HashMap<String, Object> inFilterParams = new HashMap<String, Object>();
  inFilterParams.put("school", "Hong Kong Secondary School");
  inFilterParams.put("class", "S5");
 
  // Prepare parameters for query
  HashMap<String, Object> inParams = new HashMap<String, Object>();
  inParams.put("subject", "Physics");
 
  studentList = studentRepository.doQueryWithFilter(
    "filterBySchoolAndClass", "query1",
    inFilterParams, inParams);
 
  return studentList;
 }
}

Spring Data Hibernate Database Repository (version control) Data (computing) Spring Framework Annotation

Published at DZone with permission of Boris Lam, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Projections/DTOs in Spring Data R2DBC
  • Testcontainers With Kotlin and Spring Data R2DBC
  • How to Store Text in PostgreSQL: Tips, Tricks, and Traps

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!