Search code examples
hibernatecriteriadefault-constructor

How can I set a @Transient field value after query? Using Hibernate Criteria for query


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?


Solution

  • 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.