查询后如何设置@Transient 字段值?使用 Hibernate Criteria 进行查询

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

让我详细描述问题以避免 X-Y 情况。

我想使用 Hibernate 执行 LIKE 查询以检索 table Product 中的注册表,其中 ProductUser 有我的输入字符串作为全名。 SQL 中的某些内容,例如:

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

我对 Hibernate Criteria 很满意,但在这种情况下,它似乎无法组合在 Criteria 中搜索的列值(我不想生成一些自定义的 Criteria),所以我尝试使用Restriction.sqlRestriction(),但我发现有些情况下createAlia()很容易,而sqlRestriction是不可能的,比如:

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

所以,我正在考虑另一种解决方案:在User中创建一个@Transient字段来存储全名,连接first_name" "和[=23] =], 因为现在数据库中不存在名为 full_name 的列,我不想触及 table 结构,这需要修改生产数据库。

如果我在 User class 的默认构造函数中声明了 full_name 字段,当我从数据库中检索一些 User 实体时,这个字段是否包含 first_name + " " + last_name 如我所料,还是 null?

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?

它将保存字符串 "null null",因为在填充字段之前会调用默认构造函数。

实体是一个简单的 Java class。因此,如果您执行 new Persist()Class<Persist>.newInstance(),则始终首先调用默认构造函数。第二种方式是 Hibernate 如何创建持久性 classes 的对象。

而且这种方法不会解决你的任务,因为

CONCAT(first_name, ' ', last_name) LIKE ?

不一样

first_name LIKE ? or last_name LIKE ?

I don't want to generate some customized Criteria aside

我建议你这样做。我以前写过这样的限制

您也可以尝试使用 @Formula,如上文 link 所述。