Home > Back-end >  Loading Blaze-persistence entity view by JPA specification
Loading Blaze-persistence entity view by JPA specification

Time:09-23

I have a "vanilla" JPA specification prepared for certain entity. I also have Blase-persistence entity view interface prepared for the same entity. How can I load that entity view using prepared JPA specification?

Edit: Currently, I'm using this specification like so:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<EntityClass> query = cb.createQuery(EntityClass.class);
Root<EntityClass> root = query.from(EntityClass.class);
query.where(specification.toPredicate(root, query, cb));
EntityGraph graph = entityManager.getEntityGraph(entityGraphName);
TypedQuery<EntityClass> = entityManager.createQuery(query)
.setHint("javax.persistence.loadgraph", graph);
List<EntityClass> result = typedQuery.getResultList();

After that, I'm converting list of entities into list of projections. Right now, I'm trying to replace both entity graphs and projections with entity views in similar scenario, with class for entity view coming as parameter.

CodePudding user response:

You can convert the CriteriaQuery, or actually BlazeCriteriaQuery, to a Blaze-Persistence CriteriaBuilder as outlined in the quickstart which would look roughly like this:

// This is a subclass of the JPA CriteriaBuilder interface
BlazeCriteriaBuilder cb = BlazeCriteria.get(criteriaBuilderFactory);
// A subclass of the JPA CriteriaQuery interface
BlazeCriteriaQuery<EntityClass> query = cb.createQuery(EntityClass.class);
Root<EntityClass> root = query.from(EntityClass.class);
query.where(specification.toPredicate(root, query, cb));
// Finally, transform the BlazeCriteriaQuery to the Blaze-Persistence Core CriteriaBuilder
CriteriaBuilder<EntityClass> builder = query.createCriteriaBuilder(entityManager);

At this point, you can apply a EntityViewSetting onto that query and retrieve the results as outlined in the entity-view quickstart:

CriteriaBuilder<MyEntityView> viewBuilder = evm.applySetting(EntityViewSetting.create(MyEntityView.class), builder );
List<MyEntityView> myViews = viewBuilder .getResultList();
  • Related