Java – a common JPA repository for multiple entities
I have several entities and use the spring data JPA repository and specifications to query my database Therefore, I created a generic class specbuilder to build my query based on my query descriptor
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 Repository:
public interface Entity1DAO extends Repository<Entity1,Long>,JpaSpecificationExecutor { }
and
public interface Entity2DAO extends Repository<Entity2,JpaSpecificationExecutor { }
Now I have three things I'm not sure: 1) is the use of this general specbuilder clean?
2) Is there any way to avoid writing those repository interfaces for each entity? Let's talk about a common repository?
3) The myquerydescriptor class has a method that returns an entity instance that will be queried What is a concise method to obtain the corresponding repository based on entity classes to avoid switching cases? I'm considering adding annotations with specific repository classes to each entity, but it feels a little smelly I should create a factory and inject a map
Entity1.class => Entity1DAO Entity2.class => Entity2DAO
?
Solution
You can use entity inheritance and spring expression language (spiel) to make repository problem calls on the correct entity Just like I updated here last time