Hibernate Persistence Context and Projections

Good morning.

I am wanting to reduce the amount of memory generally a query is using.

I am using Spring Boot Data and Hibernate 5.6.

I have attempted to return an interface projection via a native query using Spring’s annotation driven support but I have read somewhere that all this may really do is fetch the underlying entities and add them to the context and then create proxies over them I.e. still loads and manages the underlying entity?

I’d have assumed that with the projection interface, the entity would not be managed is it’s essentially read only and especially if its a native query?

Any clarification would greatly help!

Thank you for your time.

Even if Spring Data Projections tries to apply some optimizations, what you read is true. It might still read the whole entity and hence be more memory intensive.

I’d recommend you to look into Blaze-Persistence Entity-Views which you can imagine like Spring Data Projections on steroids. It will not only make sure that the underlying query is optimal according to what you want to fetch, but also create no entities whatsoever.

1 Like

Thank you.

I have followed this:


    public EntityViewManager entityViewManager(CriteriaBuilderFactory criteriaBuilderFactory) {
        EntityViewConfiguration defaultConfiguration = EntityViews.createDefaultConfiguration();
        return defaultConfiguration.createEntityViewManager(criteriaBuilderFactory);

public List<MyViewDTO> getViews(){
 CriteriaBuilder<MyEntity> criteriaBuilder = criteriaBuilderFactory.create(entityManager, MyEntity.class, "c")
      .orderBy("c.id", true);

        CriteriaBuilder<MyBlazeEntityView> entityCiewCriteriaBuilder = entityViewManager.applySetting(EntityViewSetting.create(MyBlazeEntityView.class), criteriaBuilder);
        List<MyBlazeEntityView> views = campaignEntryViewCriteriaBuilder.getResultList();
//Further code...

Would this result in what I want where there are no actual entities being managed in the persistence context?

Thank you for your great help!

That’s correct :slight_smile:
When you enable SQL logging, you should see that only the columns that are relevant for the entity view are fetched.