Select collections with HQL

2019-07-02 03:17发布

问题:

I have the following classes:

Person.java

class Person {
    String name;
    Set<Hotel> visitedHotels;
    String someOtherData;

    public Person() {}

    public Person(String name, Set<Hotel> visitedHotels) {
        this.name;
        this.visitedHotels = this.visitedHotels;
    }

    // getters & setters
}

Hotel.java

class Hotel {
    // some code 
}

For security reasons "someOtherData" should sometimes not be loaded.

So I tried the following HQL:

select new Person( p.name , elements(p.visitedHotels) ) from Person p

or

select new Person( p.name , hotels ) from Person p left join p.visitedHotels hotels

But it doesn’t work - error: Unable to locate appropriate constructor on class Person.

Is there a possibility to select the collection of hotels together with the person name?

回答1:

Take a look at Blaze-Persistence Entity Views with collection mappings. This might just be what you are looking for: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#collection-mappings

Allows to have a separate DTO like

@EntityView(Person.class)
interfae PersonView {
    String getName();
    Set<Hotel> getVisitedHotels();
}

Usage in the query like

CriteriaBuilder<PersonView> cb = entityViewManager.apply(
    EntityViewSetting.create(PersonView.class),
    criteriaBuilderFactory.create(Person.class)
);

List<PersonView> list = cb.getResultList();

Creates a query like

SELECT person.name, visitedHotels_1 FROM Person person LEFT JOIN person.visitedHotels visitedHotels_1

Since you seem to be using this for visualization, I recommend mapping Hotel as entity view too.