Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL and inner classes (such as builders)

Tags:

java

hibernate

Consider a Result DTO employing a builder pattern:

package com.example;
public class Result {
    int someValue;

    public static class Builder {
        private final Foo foo;
        private final Bar bar;

        public Builder(Foo foo, Bar bar) {
            this.foo = foo;
        }

        public Result build() {
            Result r = new Result();
            r.someValue = /* compute value based on supplied Foo and Bar */;
            return r;
        }
    }
}

Now, I want to create the builder in an HQL query, such as:

select new Result.Builder(f, b) from Foo f, Bar b where ...

However, I end up with error

Unable to locate class [com.example.Result.Builder]

One solution is to move the Builder to a separate class, but I like the Builder neatly packed with its entity.

Is there a way, a syntax to make Hibernate recognize an inner class in the select clause?

like image 508
prook Avatar asked Jan 06 '23 15:01

prook


1 Answers

It turns out I found the solution in the end; The proper syntax is fully qualified name with a $ separator of inner class, such as:

select new com.example.Result$Builder(f, b) from ...
like image 150
prook Avatar answered Jan 11 '23 18:01

prook