Selecting your own collections defined with @ElementCollection from Entities in JPA

Let's assume we have an Entity of this type:

@Entity
@Table(name="User")
public class User {
  @Id
  long id;

  @ElementCollection
  List<String> phones;
}

      

My goal is to have a complete list of phones for all users, for example: "SELECT x.phones FROM User x"

I tried to build a JPA data query like this:

@Query("SELECT x.phones FROM User x")
List<String> findAllPhones();

      

But I am getting this exception:

org.hibernate.QueryException: not an entity
        at org.hibernate.hql.internal.ast.tree.FromElementType.renderIdentifierSelect (FromElementType.java:188)

I had to resort to my own SQL query to solve the problem. Otherwise I will have to wrap the phone number inside the new object, but I definitely want to avoid that.

Is there a way to solve this problem using only JPA, or (even better) only Spring JPA Data Methods?

+3


source to share





All Articles