0

There is a column that's so huge, it slows the entire query speed. So i need to ommit the one, only give when actualy needed. I've tried this solution:

@Query("SELECT new Account (a.name) From Account a Where a.id = :id)

The above code will retrive the id column data.When I try to use other getter,obviously the rest property are all null. but when it comes with other entity relation for example:

//The account entity code
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    @NotFound(action = NotFoundAction.IGNORE)
    private User user;
/**
The user side code is ommitted
**/
@Query("SELECT new Account (a.name,a.user) From Account a)

it will generarte these sql query:

inner join
        user user3_ 
            on account0_.user_id=user3_.id 

However, when we using the normal jpa method like

@Query("SELECT a FROM Account a WHERE a.id = :id")
Account getById(UUID id)

we can easily get the user entity with the getter method:

Account acc = accountRepository.getById(id);
User user = acc.getUser();

Not the inner join sql query;

How can I retrieve the paritcular association entity columns with getter?

Can it be possible to achieve with jpa?

Yuzuha
  • 92
  • 2
  • 12
  • calling select new Account(X,Y) is a constructor query, and returns plain java objects using only the data you pass in - hence anything else is null, and the java object is unmanaged, so it does not use any mappings you might have - it is effectively a non-entity for all JPA purposes. If you want user to be fetched lazily, it would need to be a managed entity (see @cerdoc's answer), - but why bother? Otherwise, you could query for Account as you have, and then querying for the user separately if/when you need it. You then control if/when/where a query for it gets executed. – Chris Mar 07 '22 at 15:53

1 Answers1

0

This post should help : How to lazy load an entity attribute using JPA

Prior I strongly recommend you to understand what lazy loading is in JPA and how it works. These one could help : What is lazy loading in Hibernate? and Difference between FetchType LAZY and EAGER in Java Persistence API?

cerdoc
  • 473
  • 2
  • 8
  • Thks, turns out I misunderstand the point, lazy load the attribute can perfectly solve this situation. – Yuzuha Mar 08 '22 at 02:13