Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic JPA repository for multiple entities

I have several entities and use Spring Data JPA repositories with specifications query my database. Therefore I created a generic class SpecBuilder to build my queries based on a query description (MyQueryDescriptor).

public class Specs {
  public static <T extends MyEntityIFace> Specification<T> myfind(final MyQueryDescriptor qDesc) {
    return new Specification<T>() {
      @Override
      public Predicate toPredicate(Root<T> root, 
               CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
        try {
          return SpecBuilder.mySpec(root, criteriaQuery, criteriaBuilder, qDesc);
        } catch (Exception e) {
          ...handle error...
        }
      }
    };
  }
}

My repositories:

public interface Entity1DAO extends Repository<Entity1,Long>, 
                                    JpaSpecificationExecutor {
}

and

public interface Entity2DAO extends Repository<Entity2,Long>, 
                                    JpaSpecificationExecutor {
}

Now there are 3 things I am not quite sure about:
1)
Is this use of a generic SpecBuilder a clean design?

2)
Is there a way to avoid writing those repository interfaces for each entity? Let's say a generic repository?

3)
The MyQueryDescriptor class has a method to return an instance of an Entity, which will be queried.
What would be a clean way to obtain the according repository based on the entity class, avoiding a switch case? I was thinking about putting an annotation with the specific repository class to each entity but it feels a bit smelly.
Should I create a factory and inject a map like

Entity1.class => Entity1DAO
Entity2.class => Entity2DAO

?

like image 676
Tobi Avatar asked Oct 01 '15 06:10

Tobi


People also ask

Do you need a Repository for each entity?

It depends on your logic and how "important" are every entity. For example, if you had the entities User and Address you could have UserRepository and AddressRepository. But only UserService, with methods like addAddress(User user, Address address)...

Which is better CrudRepository or JpaRepository?

Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.

What is difference between PagingAndSortingRepository and JpaRepository?

PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.


1 Answers

You can use entity inheritance and use Spring Expression Language (SpEL) to make repository issue calls on right entities. Like in my last update here

like image 96
asm0dey Avatar answered Sep 17 '22 23:09

asm0dey