Hibernate count collection size without initializing

后端 未结 3 1800
无人共我
无人共我 2020-11-28 07:05

Is there a way I can count the size of an associated collection without initializing?

e.g.

Select count(p.children) from Parent p

(

3条回答
  •  温柔的废话
    2020-11-28 07:50

    You can use Session#createFilter which is a form of HQL which explicitly operates on collections. For example, you mention Parent and Children so if you have a Person p the most basic form would be:

    session.createFilter( p.getChildren(), "" ).list()
    

    This simply returns you a list of the children. It is important to note that the returned collection is not "live", it is not in any way associated with p.

    The interesting part comes from the second argument. This is an HQL fragment. Here for example, you might want:

    session.createFilter( p.getChildren(), "select count(*)" ).uniqueResult();
    

    You mentioned you have a where clause, so you also might want:

    session.createFilter( p.getChildren(), "select count(*) where this.age > 18" ).uniqueResult();
    

    Notice there is no from clause. That is to say that the from clause is implied from the association. The elements of the collection are given the alias 'this' so you can refer to it from other parts of the HQL fragment.

提交回复
热议问题