How to filter selected fields through Spring JPA using JPQL?

Asked

Viewed 448 times

1

I would like to know how to proceed to filter selected fields using JPQL within the JPA/Hibernate implementation?

The following scenario will be presented to facilitate understanding, following class diagram below:

Diagrama de classe onde demostra relacionamento de uma entidade Person e Phone

It is important to present the relationship strategy used. The person class is just a formal entity, containing default fields and settings. But, the relationship with Phone follows the following strategy:

    @ElementCollection
    @CollectionTable(
            name = "phones",
            joinColumns = @JoinColumn(name = "person_id"),
            uniqueConstraints = @UniqueConstraint(columnNames = "number"),
            schema = "profile",
            indexes = {@Index(columnList = "number")}
    )
    private Set<PhoneEntity> phones = new HashSet<>();

Already, the Phone class, follows the following implementation:

@Data
@Embeddable
public class PhoneEntity {

    @Column(length = 9)
    private String number;

    @Column(length = 2)
    private String areaCode;

}

Strategy is used @ElementCollection for being a simple class.

So, how do I pick up only the phones in one query? Ex:

select p.phones from Person p;
  • 1

    You can try doing by explicitly explaining the Join: SELECT ph FROM Person p JOIN p.phones ph. It came to test so?

  • What my kind of comeback would be?

  • 1

    A Set<PhoneEntity>

  • I was able to solve it here, @Dherik. Actually, I can’t create a Repository for him even because he’s an entity. But, on the other hand, I created a service and a control only to treat business pertinent to the Phone entity. Thank you! If you would like to answer the question, I will validate it as a valid answer. Gratitude!

1 answer

1


You can try doing by explicitly explaining the Join:

SELECT ph FROM Person p JOIN p.phones ph

And the expected return is the same as the entity mapping:

Set<PhoneEntity>

The final code would look something like this:

String jpql = "SELECT ph FROM Person p JOIN p.phones ph";
Query query = em.createQuery(jpql);

Set<PhoneEntity> phones = query.getResultList();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.