Select collections with HQL

六眼飞鱼酱① 提交于 2019-12-14 03:49:33

问题


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.



来源:https://stackoverflow.com/questions/39491812/select-collections-with-hql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!