1

I have an entity, which has multiple(lets say more than 5) fields in it. I want to list only 2 of the fields in entity. I managed to do it with Entity Manager and JPA Query. In the code below, I added how I did it with entity manager, but it may not be optimal solution. What I want to ask is, can I do that with using the EntityGraph?

        List<Object[]> test = entityManager.createQuery("SELECT c.a, c.b FROM TestClass c WHERE c.id = :id", Object[].class)
                .setParameter("id", id)
                .getResultList();
        TestClassResult testClassResult = new TestClassResult();
        for (Object[] row : test) {
            testClassResult.setA((BigDecimal) row[0]);
            testClassResult.setB((BigDecimal) row[1]);
        }

2 Answers 2

1

As far as I know, an implementation is allowed to fetch only what you specify when registering an entity graph as fetch graph (different from a load graph), but at least Hibernate does not support this.

Anyway, DTO projections are usually the way to in such a case anyway and I think this is a perfect use case for Blaze-Persistence Entity Views.

I created the library to allow easy mapping between JPA models and custom interface or abstract class defined models, something like Spring Data Projections on steroids. The idea is that you define your target structure(domain model) the way you like and map attributes(getters) via JPQL expressions to the entity model.

A DTO model for your use case could look like the following with Blaze-Persistence Entity-Views:

@EntityView(TestClass.class)
public interface TestClassResult {
    @IdMapping
    Integer getId();
    BigDecimal getA();
    BigDecimal getB();
}

Querying is a matter of applying the entity view to a query, the simplest being just a query by id.

TestClassResult a = entityViewManager.find(entityManager, TestClassResult.class, id);

The Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

Page<TestClassResult> findAll(Pageable pageable);

The best part is, it will only fetch the state that is actually necessary!

Sign up to request clarification or add additional context in comments.

Comments

0

as far as I know, entity graphs define which attributes to fetch from the database so you can fetch the 2 attributes eagerly and the other 3 lazily, "Thorben Janssen" has a good article on his website about graphs, another way to exclusively fetch selected attributes is to use DTO Projections, he also does have a good article touching the subject.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.