In Hibernate Query Language (HQL), you can return a new object from a query by using the new
operator and specifying the fully qualified name of the class followed by the constructor arguments.
Here is an example of how to return a new object from a query in HQL:
List<Person> people = session.createQuery("SELECT new Person(p.firstName, p.lastName) FROM Person p", Person.class).list();
In this example, the query returns a list of Person
objects by calling the Person
constructor and passing in the firstName
and lastName
properties of each Person
entity. The Person.class
argument specifies the type of the returned objects.
You can use this approach to return a new object from a query in HQL by specifying the fully qualified name of the class and the constructor arguments. You can also customize this approach by using different constructor arguments or by using different types of queries, such as a SELECT
statement or a FROM
clause.
Note that you can also use the SELECT
clause to return properties of the entity, rather than a new object. For example, you can use the SELECT p.firstName, p.lastName FROM Person p
query to return the firstName
and lastName
properties of each Person
entity.