So far whenever we are executing the query, we are getting that entire entity object. But sometimes it is desirable to retrieve only a couple of columns. For example, if I want the product name along with its category name, we can create a query for the same, which is called projection. To demonstrate the same, let's go and comment this out, and then write a new function called get product name with category names. Since I don't have this function, I press Command one or Ctrl one on Windows to auto generate that function, press tab, select the package level, and then press enter. Let's get it off the to do this time we're going to create a query a bit different than previous queries.
I'll say string HQ equals to select product name, come on category dot category name from product. As you can see, this is a property coming from directly the product class. But category name is a member of the category object, which is a member of the product here. Now we can see here query equals to session dot create query, we have to supply the SQL and the desired data type. All this time we gave product as a type or a category as a type here, so that we got a list of category or list of products. But this time, we are getting two strings instead of an entire product object.
Now these come as an array of two elements, so we can say here that it is an object or a class. So now the return value of session dot create query is a query object, which gives a list of object array element so I'm going to press your command one, press enter, you'll see that we got a query representing an object array. So in order to Get the data, we'll simply say query dot get result list, assign that to a variable called the list. But this time when I press Command one, you will see that it's a list of object array, where each array will have two elements in it, one product name, and the other one category name. Just to prove the point, let's loop that we say give me one object array called the data from the list. And then we're going to print the data of zero which is going to be the product name, plus something like this where data of one which is the category name going to be printed.
I save this around the same. This time there is no product object created, but we still be able to get the product names along with the category names