简体   繁体   中英

Spring Data use parameters in select clause of @Query

Goal

I am trying to define a generic query that allows me to list the possible (distinct) values of a property, possibly nested, of an entity. The goal is to have a drop down selection for the end user to choose from when filtering down the list of entities.

Setup

@Entity
public class Customer {
  @Id @GeneratedValue Long id;
  @NotNull String name;
  @Embedded @NotNull Address address;
  ...
}

@Embeddable
public class Address {
  String country;
  String city;
  String postalCode;
  String street;
  String number;
  ...
}

public interface CustomRepository {
  @Query("select distinct ?1 from #{#entityName}")
  List<String> findAllValues(String value);

  @Query("select distinct ?1.?2 from #{#entityName} where ?1 IS NOT NULL")
  List<String> findAllSubValues(String path, String value);
}

public interface RepositoryCustomer extends
    CrudRepository<Customer, Long>,
    JpaSpecificationExecutor<Customer>,
    CustomRepository {}

Usage

The query could then be used as follows to show a selection box for filtering down the customers list based on their address country:

public class SelectionComponent {
  @Autowired RepositoryCustomer repo;    
  ComboBox<String> select = new ComboBox<String>();

  @PostConstruct
  void onPostConstruct() {
    select.setItems(repo.findAllSubValues("address", "country"));
  }
}

Problem

Compiling the above setup results in follow exception:

org.hibernate.QueryException: Parameters are only supported in SELECT clauses when used as part of a INSERT INTO DML statement

Question

It seems this is not supported. Any alternative suggestions?

To not leave this unanswered. My solution in general has been to avoid trying to express relational or complex queries when it comes to JPA and Spring data.

I have come to prefer creating specific (single purpose) database views for such needs and have a very simple query in my "business layer". In some sense, this creates duplication or denormalization in the database layer, but greatly reduces the complexity required from overlay frameworks such as JPA and Spring data.

In this particular case, I would have a customer country database view that I would map to a JPA entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM