Search code examples
javajpaentitymanager

How to read specific variables of an entity from repository using a query?


Assume that we have a persisted Entity object which has 10 variables, if I do for example repository.read(id) or repository.findById(id) I will get back an Entity object with every variable which is set from the repository.

Is there any way using JPAQuery or EntityManager or any other possible way, that I can make the call on the repository and get back the Entity object BUT without a specific variable being fetched as well?

I have tried the following, but it doesnt seem to do anything, still brings the Set within the response:

JPAQuery<Fruit> query = new JPAQuery<>(entityManager);
QFruit fruit = QFruit.Fruit;
Set<Apple> apple = new HashSet<Apple>();
query.select(fruit).from(fruit).where(fruit.id.eq(fruitId))
.createQuery().getParameters().remove(apple);
return query.fetchOne();

Solution

  • Eventually I was trying to read specific data from an entry of a Table, because the specific table has so many data it was harassing the performance, thus bringing the whole entity just for 1 or 2 variables was not correct. Eventually what helped me was Tuple. Using JPAQuery you have the advantage that you can select specific variables to be brought back from the search. e.g.

        JPAQuery<MyObject > query = new JPAQuery<>(entityManager);
        MyObject myObject  = QMyObject.MyObject ;
        Tuple response = query.select(myObject.id, myObject.version)
        .where(myObject.id.eq("12345")).or(myObject.version.eq("12345")).fetchaAll();
    

    Then you can easily retrieve the Tuple object and handle the values as an array.