0

Let me describe the question in full details to avoid the X-Y situation.

I want to use Hibernate to do a LIKE query to retrieve registries in table Product where the Product's User has my input string as full name. Something in SQL like:

SELECT * FROM product WHERE id_user IN (SELECT id_user FROM users WHERE CONCAT(first_name, ' ', last_name) LIKE ?)

I am happy with Hibernate Criteria, but in this case it seems to have no way to do combining columns values searching in Criteria (I don't want to generate some customized Criteria aside), so I am trying to use Restriction.sqlRestriction(), but I found that in some case createAlia() is quite easy while sqlRestriction is impossible, such as:

criteria.createAlias("user.supervisor.teamleader", "uT");

So, I am considering another solution: creating a @Transient field in User to store the full name, concatenating first_name, " ", and last_name, because now a column named full_name doesn't exist in database, and I don't want to touch table structure, which requires modification to production database.

If I declare full_name field in the default constructor of User class, when I retrieve some User entity from database, will this field holds first_name + " " + last_name as I expect, or will it be null?

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
WesternGun
  • 11,303
  • 6
  • 88
  • 157

1 Answers1

0

If I declare full_name field in the default constructor of User class, when I retrieve some User entity from database, will this field holds first_name + " " + last_name as I expect, or will it be null?

It will hold the string "null null", because of a default constructor is invoked before a fields population.

An entity is a simple Java class. So a default constructor always is invoked in the first place, if you do new Persist() or Class<Persist>.newInstance(). The second way is how Hibernate creates objects of persistent classes.

And this approach will not solve your task, because of

CONCAT(first_name, ' ', last_name) LIKE ?

is not the same

first_name LIKE ? or last_name LIKE ?

I don't want to generate some customized Criteria aside

I would advise you to do it. I have written such a restriction some time before

How can I concatenate two properties into one property using hibernate criteria query

You can try to use a @Formula too, as described by a link above.

Community
  • 1
  • 1
v.ladynev
  • 19,275
  • 8
  • 46
  • 67
  • About the first point, thank you because I don't exactly know the order of construction of an entity and its population. About the second point, my question is well defined because the user input maybe "John", "White" or "John White", with "John" as name and "White" as surname. And the third point, to my surprise, I just found the same post after asking this question... Sometimes I don't know the exact term, such as "derived property" in this case ....Thx. Will accept your answer. – WesternGun Mar 14 '16 at 12:11