java 在 Hibernate 中使用 IF 构造

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4978024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:54:25  来源:igfitidea点击:

Using IF construction in Hibernate

javasqlhibernatehql

提问by evm

I'm using the construction "if" in HSQL:

我在 HSQL 中使用构造“if”:

String q = "SELECT id, name, " +
                "IF (ABS(name) > 0, LPAD(ABS(name), 4, '0'), name) AS tord " +
                "FROM table where city= " + cityId + " order by tord";

    Query query = session.createSQLQuery(q);
    List<Object[]> list = query.list();
    session.getTransaction().commit();
    session.close();

And now i want to refactor this piece of code with HQL. How can i do this? Thanks.

现在我想用 HQL 重构这段代码。我怎样才能做到这一点?谢谢。

回答by Vladimir Korolev

Option 1.

选项1。

Replace IF with CASE:

将 IF 替换为 CASE:

(case when ABS(name) > 0 then LPAD(ABS(name), 4, '0' else name end) AS tord

See HQL documentationfor details.

有关详细信息,请参阅HQL 文档

Option 2.

选项 2。

HQL supports native functions. If you encapsulate calculations in custom SQL function you can write something like:

HQL 支持原生函数。如果您将计算封装在自定义 SQL 函数中,您可以编写如下内容:

select t.*, paddNumber(t.name, 4) as tord from TableEntity t 
where t.city = :city order by tord

Have no environment to check but think each result record will be represented as Object[]. Where first element will contain your entity and second will contain tord.

没有要检查的环境,但认为每个结果记录都将表示为 Object[]。其中第一个元素将包含您的实体,第二个将包含 tord。

Option 3.

选项 3。

If possible, rewrite application logic. There are different ways to add required padding to field 'name' before saving record. This will remove unnecessary calculation in DB during sorting.

如果可能,重写应用程序逻辑。在保存记录之前,有多种方法可以将所需的填充添加到字段“名称”。这将在排序期间删除 DB 中不必要的计算。